Friends
There is a town with N citizens. It is known that some pairsof people are friends. According to the famous saying that “The friends of myfriends are my friends, too” it follows that if A and B are friends and B and Care friends then A and C are friends, too.
Your task is to count how many people there are in thelargest 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 isthe number of town's citizens (1≤N≤30000) and M is the number ofpairs of people (0≤M≤500000), which are known to be friends. Eachof 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. Therecould be repetitions among the given pairs.
Output
The output for each test case should contain one number denoting how manypeople there are in the largest group of friends.
Sample Input | Sample Output |
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 10 1 2 9 10 8 9 | 3 6 |
Problem source: Bulgarian National Olympiad in Informatics2003
Problem submitter: Ivaylo Riskov
Problem solution: Ivaylo Riskov
你朋友的朋友也是你的朋友,求,各个集合中元素最多的集合的元素个数
代码:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX 50010
struct uftree
{
int cnt;
int rank;
int parent;
} set[MAX];
void make_set(int n)
{
int i;
for(i=0; i<=n; i++)
{
set[i].cnt=1;
set[i].rank=0;
set[i].parent=i;
}
}
int set_find(int x)
{
if(set[x].parent==x)
return x;
else
return set[x].parent=set_find(set[x].parent);
}
void set_join(int x,int y)
{
int a=set_find(x);
int b=set_find(y);
if(set[a].rank>set[b].rank)
{
set[b].parent=a;
if(a!=b)
set[a].cnt+=set[b].cnt;
}
else
{
set[a].parent=b;
if(a!=b)
set[b].cnt+=set[a].cnt;
if(set[a].rank==set[b].rank)
{
set[b].rank++;
}
}
}
int cmp(const void *a,const void *b)
{
uftree *p1=(uftree *)a,*p2=(uftree *)b;
return p2->cnt-p1->cnt;
}
int query(int n)
{
qsort(set,n+1,sizeof(set[0]),cmp);//按元素个数排序
return set[0].cnt;
}
int main()
{
int t,n,m,i,a,b,ans;
scanf("%d",&t);
{
while(t--)
{
scanf("%d%d",&n,&m)&&(n||m);
make_set(n);
for(i=0; i<m; i++)
{
scanf("%d%d",&a,&b);
set_join(a,b);
}
ans=query(n);
printf("%d\n",ans);
}
}
return 0;
}
如有疑惑请见上篇
http://blog.csdn.net/u012860428/article/details/38167843