比赛看到这个题目时候,心花怒放啊,朋友这个题和how many tables这个题目一样嘛,并查集,直接就把自己代码交了,后来一看,傻眼了,得输出的是集合中个数最多的数目。后来直接在合并的代码中小小的改动就行了。其实也可以在每次查后把什么孙子,曾孙全变为儿子。再来一个遍历,把不同门派的弟子统计一下,每次选规模大的数就行了。
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 |
#include<iostream> using namespace std; int index[30001]; int how[30001]; int getfather(int n) { while(index[n] != n) { n = index[n]; } return n; } int main() { int m; cin >> m; while(m--) { int peo,pair,ans = 0; cin >> peo >> pair; for(int i = 1;i <= peo;i++) { index[i] = i; how[i] = 1; } int fathera; int fatherb; for(int j = 0;j < pair;j++) { int a,b; cin >> a >> b; fathera = getfather(a); fatherb = getfather(b); if(fathera != fatherb) { index[fatherb] = fathera; how[fathera] += how[fatherb]; if(ans < how[fathera]) { ans = how[fathera]; } } } cout << ans << endl; } return 0; }
ACM训练二D题