并查集模板

//并查集模板
//11.11.2015 by blacktea   >>>>>_<<<<<
// this version isn't the best I will change it time by time
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#define LL long long
using namespace std;
int i,j,k,n,m,t,pre[1000000],rounte[100000],a,b;
void init()//初始化
{
    memset(rounte,0,sizeof(rounte));
    for(i=1;i<=n;i++)
        pre[i] = i;
}

int toGetFarther(int x)//获得他们的祖宗
{
    int x1 = x;
    while(pre[x]!=x)x = pre[x];
    if(pre[x1]!=x) pre[x1] = x;
    return x;
}
void join(int x,int y)//判断他们是否是一个祖宗
{
    x = toGetFarther(x);
    y = toGetFarther(y);
    if(x!=y)pre[x] = y;
}
int main()
{
   while(scanf("%d%d",&n,&m)!=EOF)
   {
       int sum = 0;
       init();
      while(m--)
      {
        scanf("%d%d",&a,&b);
        join(a,b);
      }
      for(i=1;i<=n;i++)
      {
           int r = i;
           while(pre[r]!=r)
               r = pre[r];
           rounte[r]++;
      }
      for(i=1;i<=n;i++)
        if(rounte[i])sum++;//判断祖宗的个数即为有多少个独立的区间
      printf("%d\n",sum);
   }
    return 0;
}

上面那个有点乱搞这个比较正统

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int n,l1,a,fa[200],am[200];
struct edge{
   int x,y,v;
}e[20000];
void init()
{
    for(int i=0;i<n;i++)
    {
        fa[i] = i;
        am[i] = 1;
    }
}
int findFarther(int x)
{
    while(fa[x]!=x){
        x = fa[x];
    }
    return x;
}
void Union(int x,int y)
{
    int rootx = findFarther(x),rooty = findFarther(y);
    if(rootx!=rooty){
        if(am[rootx]>am[rooty]){
            fa[rooty] = rootx;
            am[rootx]+=am[rooty];
        }
         else{
            fa[rootx] = rooty;
            am[rooty]+=am[rootx];
         }
    }
}
void UnionFind()
{
    for(int i=0;i<l1;i++)
    {
        Union(e[i].x,e[i].y);
    }
}
int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        init();
        l1 = 0;
       for(int i=0;i<n;i++)
         for(int j=0;j<n;j++)
        {
            scanf("%d",&a);
            e[l1].x = i;
            e[l1].y = j;
            e[l1].v = a;
            l1++;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值