本文主要是介绍UVA 10608 - Friends (并查集),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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 |
题意:给定n个人m种朋友关系,求最大朋友圈。
思路:并查集。
代码:
#include <stdio.h>
#include <string.h>int t, n, m, i, j, parent[30005], sum[30005], ans;
int a, b;int find(int x) {if (x == parent[x])return parent[x];elsereturn find(parent[x]);
}
int main() {scanf("%d", &t);while (t --) {ans = 0;scanf("%d%d", &n, &m);for (i = 1; i <= n; i ++) {parent[i] = i;sum[i] = 1;}for (i = 0; i < m; i ++) {scanf("%d%d", &a, &b);int pa = find(a);int pb = find(b);if (pa != pb) {parent[pa] = pb;sum[pb] += sum[pa];if (ans < sum[pb])ans = sum[pb];}}printf("%d\n", ans);}return 0;
}
这篇关于UVA 10608 - Friends (并查集)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!