hdu_1232

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int pre[1010]; //里面全是掌门

int unionsearch(int root)  //,pre[15]=3就表示15号大侠的上级是3号大侠。
{                        //如果一个人的上级就是他自己,那说明他就是掌门人了
  int son,tre;
  son=root;
  while(root!=pre[root])  // 找到根节点
        root=pre[root];

    while(son!=root)
    {
        tre=pre[son];       // 路径压缩
        pre[son]=root;
        son=tre;
    }

return root;
}

int main()
{
    int n,m;
    int i,j,k,a,b;
    int t_a,t_b;
    while(scanf("%d%d",&n,&m)!=EOF)
    {  if(n==0)
    break;
     k=n-1;
     for(i=1;i<=n;i++)
        pre[i]=i;
     while(m--)
     {
         scanf("%d%d",&a,&b);
         t_a=unionsearch(a);
         t_b=unionsearch(b);
    //     printf("\n%d %d\n",t_a,t_b);
         if(t_a!=t_b)
         {
             pre[t_a]=t_b;
             k--;
         }
     }
     printf("%d\n",k);
    }
    return 0;
}
如果有什么不理解可以看我其他的博客上有详解

猜你喜欢

转载自blog.csdn.net/xxf_is_girl_gad/article/details/80670321
今日推荐