这算是我第一次自己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;
}