HDU_1232_并查集

http://acm.hdu.edu.cn/showproblem.php?pid=1232

第一道并查集,挺好理解的,初始化,查找根节点,连接,路径压缩。

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int pre[1005],t[1005],n,m,a,b;

int findd(int x)
{
    int root = x;
    while(pre[root] != root)    root = pre[root];
    int i = x,j;
    while(pre[i] != root)
    {
        j = pre[i];
        pre[i] = root;
        i = j;
    }
    return root;

}
void join(int a,int b)
{
    int x = findd(a),y = findd(b);
    if(x != y)  pre[x] = y;
}
int main()
{
    while(scanf("%d",&n) && n)
    {
        scanf("%d",&m);
        for(int i = 1;i <= n;i++)   pre[i] = i;
        while(m--)
        {
            scanf("%d%d",&a,&b);
            join(a,b);
        }
        memset(t,0,sizeof(t));
        for(int i = 1;i <= n;i++)
        {
            t[findd(i)] = 1;
        }
        int ans = 0;
        for(int i = 1;i <= n;i++)
        {
            if(t[i])    ans++;
        }
        printf("%d
",ans-1);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zhurb/p/5914972.html