原题:
There is a town with N citizens. It is known that some pairs of people are friends. According to the famous saying that “The friends of my friends are my friends, too” it follows that if A and B are friends and B and C are friends then A and C are friends, too.
Your task is to count how many people there are in the largest group of friends.
Input
Input consists of several datasets. The first line of the input consists of a line with the number of test cases to follow.
The first line of each dataset contains tho numbers N and M, where N is the number of town’s citizens (1 ≤ N ≤ 30000) and M is the number of pairs of people (0 ≤ M ≤ 500000), which are known to be friends. Each of the following M lines consists of two integers A and B (1 ≤ A ≤ N, 1 ≤ B ≤ N, A ̸= B) which describe that A and B are friends. There could be repetitions among the given pairs.
Output
The output for each test case should contain (on a line by itself) one number denoting how many people there are in the largest group of friends on a line by itself.
Sample Input
2
3 2
1 2
2 3
10 12
1 2
3 1
3 4
5 4
3 5
4 6
5 2
2 1
7 1
1 2
9 10
8 9
Sample Output
3
7
中文:
一个城里有n个居民,这些居民有朋友之间的关系,一个人的朋友的朋友也可以算作是朋友,最后问你这n个人当中,朋友最多的群落有多少人?
#include<bits/stdc++.h>
using namespace std;
int father[30001];
int Rank[30001];
int Find(int x)
{
if(x==father[x])
return x;
return father[x]=Find(father[x]);
}
void Merge(int x,int y)
{
x=Find(x);
y=Find(y);
if(x==y)
return;
if(Rank[x]<=Rank[y])
{
father[x]=y;
Rank[y]+=Rank[x];
}
else
{
father[y]=x;
Rank[x]+=Rank[y];
}
}
void init(int n)
{
for(int i=1;i<=n;i++)
{
father[i]=i;
Rank[i]=1;
}
}
int main()
{
ios::sync_with_stdio(false);
int n,m,t;
cin>>t;
while(t--)
{
cin>>n>>m;
init(n);
for(int i=1;i<=m;i++)
{
int a,b;
cin>>a>>b;
Merge(a,b);
}
int ans=-1;
for(int i=1;i<=n;i++)
{
ans=max(ans,Rank[i]);
}
cout<<ans<<endl;
}
return 0;
}
解答:
裸的并查集,在Rank当中保留第i个人的朋友数,合并的时候把他的朋友数加到另外一个人身上即可。