码迷,mamicode.com
首页 > 其他好文 > 详细

并查集模板

时间:2017-01-14 20:59:20      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:递归   ems   style   using   while   log   std   void   路径   

//普通并查集模板
#include<iostream>
using namespace std;
const int MAX=10004;
int fat[MAX];//存放每个节点的根节点
//找x的根节点并且把路径上的每个节点的父节点改成根节点
int find(int x) //while找根节点
{
    int rt=x;
    while(fat[rt]!=rt)
        rt=fat[rt];
    int i=x,j;
    while(i!=rt){
        j=fat[i];
        fat[i]=rt;
        i=j;
    }
    return rt;
}
int Find(int x)  //递归找根节点
{
    if(fat[x]!=x)
        fat[x]=Find(fat[x]);
    return fat[x];
}
void connect(int x,int y)   //x的根节点合并到y的根节点上
{
    int xx=find(x),yy=find(y);
    if(xx!=yy)
        fat[xx]=yy;
}
int main()
{
    return 0;
}
**********************************************************
//算点的转移次数
#include<iostream>
#include<cstring>
using namespace std;
const int MAX=10004;
int fat[MAX];//存放每个节点的根节点
int num[MAX];//记录节点的转移次数
int cnt[MAX];//某点的权值
int find(int x)
{
    if(fat[x]!=x){
        int tmp=fat[x];
        fat[x]=find(fat[x]);
        num[x]+=num[tmp];//x点转移的次数是他的转移次数加上父节点的转移次数。
    }
    return fat[x];
}
void connect(int x,int y)
{
    int xx=find(x),yy=find(y);
    if(xx!=yy){
        fat[xx]=yy;
        num[xx]++;//开始转移了一次
        cnt[yy]+=cnt[xx];//权值转移了
    }
}
int main()
{
    memset(num,0,sizeof(num));
    return 0;
}

 

并查集模板

标签:递归   ems   style   using   while   log   std   void   路径   

原文地址:http://www.cnblogs.com/--ZHIYUAN/p/6286025.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!