hdu1856(并查集的简单应用)

这算是我第一次自己ac并查集的题目,虽然题目不难,但也算是个突破吧

题意:求所有连通分量中节点数目的最大值,我用到了一个rank数组,用来记录父亲节点有几个儿子节点

代码如下:

#include<iostream>
#include<algorithm>
#include<string>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<time.h>
#include<math.h>

#define eps 1e-9
#define N 10000005
#define pi acos(-1.0)
#define P system("pause")
using namespace std;
int f[N],rank[N];
int find(int x)
{
     if(f[x] == x) return x;           //我自己记录了f[x] == x的节点的孩子节点个数
     //int t = find(f[x]);
    // rank[f[x]] = rank[x] + rank[f[x]];
     return f[x] = find(f[x]);    
}
int main()
{
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
    int n;
    while(scanf("%d",&n) != EOF)
    {
         int i;
         for(i = 0; i <= N; i++){
               f[i] = i;         
               rank[i] = 1;
         } 
         for(i = 0; i < n; i++)
         {
            int a,b;
            scanf("%d%d",&a,&b);
            int x,y;
            x = find(a);
            y = find(b);
            if(x != y)
            {
                 f[x] = y;
                 rank[y] = rank[x] + rank[y];      
            }
           // for(int j = 1; j <= 10; j++)
             // cout<<f[j]<<" ";cout<<endl;
           // for(int j = 1; j<= 10; j++)
             // cout<<rank[j]<<" ";cout<<endl;
            
         }                      
         int maxx = 0;              
         for( i = 0; i <= N; i++)
              if(rank[i] > maxx) 
                    maxx = rank[i];
        printf("%d\n",maxx);   
    }     

  //  P;                               
    return 0;    
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值