HDU 畅通工程

#include<iostream>
using namespace std;
int f[1005];
int getparent(int x){
    while(x!=f[x]) x=f[x];
    return x;
}
int merge(int a,int b){
    int t1=getparent(a);
    int t2=getparent(b);
    if(t1!=t2){
        f[t1]=t2;
        return 1;
    }
    return 0;
}
int main()
{
    int n,m,i,j,x,y;
    while(cin>>n>>m,n){
        int c=0;
        for(i=1;i<=n;i++) f[i]=i;
        for(i=0;i<m;i++){
            cin>>x>>y;
            if(merge(x,y)) c++;
        }
        cout<<n-1-c<<endl;
    }
    return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_37016724/article/details/88822442