Problem I
FRIENDS
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 one number denoting how many people 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 Informatics 2003
Problem submitter: Ivaylo Riskov
Problem solution: Ivaylo Riskov
#include<iostream>
using namespace std;
#include<string>
#include<string.h>
#include<stdio.h>
#include<cstring>
#include<math.h>
#include<queue>
#include<stdlib.h>
#include<algorithm>
#include<map>
#include<stack>
#include<vector>
//集合的不相交的并集
// 如果a[i]是正数,就指的是i的根;如果指向负数,说明i是跟,而且i这个集合的势就是-a[i]
// 递归进行路径压缩
int a[30002];
int Find( int x)
{
if( a[x]<0) return x;
else return a[x]=Find(a[x]);
}
// Union by Size
void Union( int root1, int root2)
{
if( a[root1]>=a[root2])
{
a[root2]+=a[root1];
a[root1]=root2;
}
else
{
a[root1]+=a[root2];
a[root2]=root1;
}
}
int main()
{
int T;
cin>>T;
while( T--!=0)
{
int N, M;
cin>>N>>M;
//N citizens, M pairs
for( int i=1; i<=N; ++i)
a[i]=-1;
//要用到a[1],...,a[N]
for( int i=0; i!=M; ++i)
{
int x, y;
cin>>x>>y;
if( Find(x)!=Find(y)) //如果根不相同,把根合并即可
Union(Find(x),Find(y));
}
int Min=0;
for( int i=1; i<=N; ++i)
if( a[i]<Min) Min=a[i];
cout<<-Min<<endl;
}
return 0;
}
浙公网安备 33010602011771号