北大2524題

題目鏈接:http://poj.org/problem?id=2524

並查集的簡單應用

 

#include <iostream>
using namespace std;

int father[50000],rank[50000],result;

void Make(int n)
{
 int i;
 result = n;
 for(i = 0;i < n;++i)
 {
  father[i] = i;
  rank[i] = 0;
 }
}

int Find(int x)
{
 if(x != father[x])
 {
  father[x] = Find(father[x]);
 }
 return father[x];
}

void Union(int x,int y)
{
 x = Find(x);
 y = Find(y);

 if(x != y)
 {
  if(rank[x] > rank[y])
  {
   father[y] = x;
  }
  else
  {
   if(rank[x] == rank[y])
    ++rank[y];
   father[x] = y;
  }
  --result;
 }
}

int main()
{
 freopen("in.txt","r",stdin);
 int n,m,s = 1;
 while(scanf("%d%d",&n,&m) != EOF)
 {
  if(n == 0 && m == 0)
   break;

  Make(n);

  int i,x,y;
  for(i = 0;i < m;++i)
  {
   scanf("%d%d",&x,&y);
   Union(x-1,y-1);
  }

  printf("Case %d: %d\n",s++,result);
 }
 return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章