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.
InputThe input starts with an integer T(1<=T<=25) which indicate the number of test cases. Then T test cases follow. Each test case starts with two integers N and M(1<=N,M<=1000). N indicates the number of friends, the friends are marked from 1 to N. Then M
lines follow. Each line consists of two integers A and B(A!=B), that means friend A and friend B know each other. There will be a blank line between two cases.
OutputFor each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.
Sample Input
2 5 3 1 2 2 3 4 5 5 1 2 5
Sample Output
2 4 模板题一道 就当回顾。本来答应自己不写水题的,但是是师父出的,得给点面子吧,虽然师父也觉得没意思~
#include<stdio.h> #include<string.h> #define N 1100 int n,m; int f[N],u[N],v[N]; int find(int u) { if(f[u]==u) return u; else { f[u] = find(f[u]); return f[u]; } } void merge(int x,int y) { int t1,t2; t1 = find(x); t2 = find(y); if(t1!=t2) f[t1] = t2; return; } int main() { int t,i,j,count; scanf("%d",&t); while(t --) { scanf("%d%d",&n,&m); for(i = 1; i <= n; i ++) f[i] = i; for(i = 1; i <= m; i ++) scanf("%d%d",&u[i],&v[i]); for(i = 1; i <= m; i ++) merge(u[i],v[i]); count = 0; for(i = 1; i <= n; i ++) if(f[i]==i) count ++; printf("%d\n",count); } return 0; }

探讨了如何根据朋友间的熟悉度为Ignatius的生日派对分配最少数量的餐桌,利用并查集算法实现解决方案。
1295

被折叠的 条评论
为什么被折叠?



