kuangbin_UnionFind C (HDU 1213)

过程模板 扫一下一共有几棵树 输出

#include <iostream>
#include <string>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
#define MAX 1010
using namespace std;
int father[MAX],table[MAX];
int Findfather(int x)
{
    while(x!=father[x])
        x=father[x];
    return x;
}
void Union(int x,int y)
{
    x=Findfather(x);
    y=Findfather(y);
    father[x]=y;
}
int main()
{
    int t,n,m,count;
    scanf("%d",&t);
    while(t--)
    {
        count=0;
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)
        {
            father[i]=i;
            table[i]=0;
        }
        while(m--)
        {
            int a,b;
            scanf("%d%d",&a,&b);
            Union(a,b);
        }
        for(int i=1;i<=n;i++)
        {
              int tmp=Findfather(i);
              bool same=false;
              for(int j=1;j<=count;j++)
                if(tmp==table[j])
                   {
                       same=true;
                       break;
                }
             if(!same){
                 table[++count]=tmp;
             }
        }
        printf("%d
",count);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/quasar/p/5060156.html