HDU 1232 _杭电 1232题_ 并查集的应用

来源:互联网 发布:fm2017经典球员数据库 编辑:程序博客网 时间:2024/05/16 11:36

#include <iostream>
using std::cin;
using std::cout;
using std::endl;

const int max = 1000;
int father[max];
int count;
////////////////////////
void make_set(int n)//初始化并查集 ,初始化集合数count
{
             int i;
             for( i = 0 ; i < n ; i++ )
             father[i] = i;
             count = n;
}
///////////////////////
int find_set(int n)//查找所属集合并压缩路径
{
             if(n==father[n])
             return n;
             else father[n] = find_set(father[n]);
             return father[n];
}
///////////////////////
void Union(int a,int b)//合并 ,并依情况减少集合计数 count
{
     int set_a = find_set(a);
     int set_b = find_set(b);
     //找到头,对头处理(set_a,set_b是find_set的结果,所以它们各自代表了一个集合,即各是一个根)
     if( set_a == set_b )return;
     else
     {
         father[set_a] = father[set_b];
         count--;
     }
}

int main()
{
    int N,M,i,j,k;
    while(cin>>N)
    {
                 if(N==0)break;
                
                 make_set(N);
                
                 cin>>M;
                 for( i = 0 ; i < M ; i++ )
                 {
                      cin>>j>>k;
                      Union(j-1,k-1);
                 }
                 cout<<count-1<<endl;
    }
    system("pause");
    return 0;
}