nyoj-608-畅通工程

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
int temp[1010];
int find(int n)
{
    return temp[n]==n?n:temp[n]=find(temp[n]);
}
int main()
{
    int n,m,i,a,b;
    while(scanf("%d",&n),n)
    {
        scanf("%d",&m);
        for(i=0;i<=n;i++)
            temp[i]=i;
        for(i=0;i<m;i++)
        {
            scanf("%d%d",&a,&b);
            int x,y;
            x=find(a);y=find(b);
            if(x!=y)
                temp[x]=y;
        }
        int sum=0;
        for(i=1;i<=n;i++)
        {
            if(temp[i]==i)
            sum++;
        }
        printf("%d\n",sum-1);
    }
    return 0;
}

并查集

posted @ 2013-07-24 10:07  nylg-haozi  阅读(131)  评论(0编辑  收藏  举报