HDU-1232-畅通工程 简单 赤裸 并查集

超有爱讲解 点这里

#include<iostream>
using namespace std;
#define Size 1000
int Father[Size];

int Find( int n )
{
        while( n != Father[n] )
            n = Father[n];

        int i = n;
        while( i != Father[n] )           // 路径压缩
        {
                int temp = Father[i];
                Father[i] = Father[n];
                i = temp;
        }

        return Father[n];
}

void Merge( int a, int b )
{
        int f1 = Find( a );
        int f2 = Find( b );

        if( f1!=f2 )
            Father[f1] = f2;
}

int main()
{
        int N, M;
        while( cin>>N && N!=0 )
        {
                for( int i=0; i<=N; i++ )
                    Father[i] = i;
                cin>>M;
                int a, b;
                while( M-- )
                {
                        cin>>a>>b;
                        Merge( a, b );
                }

                int ans=0;
                for( int i=1; i<=N; i++ )
                    if( Father[i] == i )
                        ans++;
                cout<<ans-1<<endl;
        }
        return 0;
}

 

posted @ 2015-07-22 09:20  _SunDaSheng  阅读(118)  评论(0编辑  收藏  举报