hdu 1232 畅通工程 并查集基础题

#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
int f[1005];
int find(int x)//把一个集合内的数连成一个串,f[x]表示x在串中的父节点,find(x),用于查找根节点。
{
    if(f[x]!=x)f[x]=find(f[x]);
        return f[x];
}
int main()
{
    int n,m;
    while(scanf("%d",&n)!=EOF)
    {
        if(n==0)break;
        scanf("%d",&m);
        int i,j,k,a,b,aa,bb,ans;
        ans=n-1;
        for(i=1;i<=n;i++)
            f[i]=i;
        for(i=0;i<m;i++)
        {
            scanf("%d%d",&a,&b);
            aa=find(a); //一开始写成了aa=f[a],找了半天没找出来,哭死。。
            bb=find(b);
            if(aa!=bb){f[aa]=bb;ans--;}
        }
        printf("%d\n",ans);
    }
    return 0;
}
/*
    并查集:用于判断两个元素是否在一个集合内。
3 4
1 2
2 3
1 3
3 1
*/

你可能感兴趣的:(并查集)