hdu-1213

贼坑的并查集

写一下我对于并查集的一些心得和想法

并查集讲的是一堆数列在几个相连的情况下的分组情况

然后是另一个人写的超好(我的偶像)

大家可以去看一下

https://blog.csdn.net/dellaserss/article/details/7724401

我的思路如下

1.首先把每个数当做它自己的集合的序列

2.然后根据得到的信息把两个集合合成一个

3最后合成了多少个就意味着有多少个人在一起吃饭。

附上我写的代码

#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;
    scanf("%d",&j);
    while(j--)
    {
    scanf("%d%d",&n,&m);
     k=n;
     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/80670042
今日推荐