Today is Ignatius' birthday. He invites a lot of friends. Now it's dinner time. Ignatius wants to know how many tables he needs at least. You have to notice that not all the friends know each other, and all the friends do not want to stay with strangers.
One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.
For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.
One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.
For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.
2 5 3 1 2 2 3 4 5 5 1 2 5
2 4
算是一道入门级别的并查集吧。T组数据,每组数据第一行n,m。 n代表n个人聚餐 m代表接下来有m行输入, 每行两个数字A,B,表示A和B两个人认识。直接或者间接认识的人坐一桌,问一共需要多少桌。
把认识的合并一下,然后再计算一下集合就行了。
#include <stdio.h> int f[1005]; void init(int n) { for(int i = 1; i <= n; i++) { f[i] = i; } } int getf(int v) { if(f[v] != v) { f[v] = getf(f[v]); } return f[v]; } void merge(int u, int v) { int t1 = getf(u); int t2 = getf(v); if(t1 != t2) { f[t1] = t2; } } int main() { int T; int n, m; int A, B; scanf("%d", &T); while(T--) { scanf("%d %d", &n, &m); init(n); for(int i = 1; i <= m; i++) { scanf("%d %d", &A, &B); merge(A, B); } int sum = 0; for(int i = 1; i <= n; i++) { if(f[i] == i) { //计算有几个集合 sum ++; } } printf("%d\n", sum); } return 0; }