畅通工程(HD1232)

原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1232

代码:

#include<iostream>
using namespace std;
int father[1001];
int findfather(int x)
{
   while(father[x]!=x)//如果x的父节点不是他本身,证明x不是根
     x=father[x];
   return x;
}
void unitnode(int x,int y)
{
   int f1=findfather(x);
   int f2=findfather(y);
   if(f1!=f2)
   father[f1]=f2;
}
int main()
{
   int country,road,a,b,count;
  while(cin>>country&&country!=0)
  {
   cin>>road;
   count=0;
   for(int i=0;i<country;i++)
        father[i]=i;
   for(int i=0;i<road;i++)
   {
     cin>>a>>b;
     unitnode(a-1,b-1);
   }
   for(int i=0;i<country;i++)
   {
     if(father[i]==i)
     count++;
   }
   cout<<count-1<<endl;
  }

}

 

posted @ 2013-05-27 10:17  supersnow0622  Views(191)  Comments(0)    收藏  举报