F - How Many Tables

比眉伴天荒 2022-03-19 11:28 251阅读 0赞

题目描述:

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.
Input
The 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.
Output
For 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

题意:

lg邀请了许多朋友来吃饭。问需要几张桌子。 在同一张桌子上的人必须相互认识 。如果A认识B B认识C。 那么可以称A与C相互认识。 
分析:
这又是一个求并查集的题目。 我们可以发现,有多少个首领就需要多少张桌子。因为各个首领之间肯定是不认识的。

  1. #include"stdio.h"
  2. #include"string.h"
  3. #include"algorithm"
  4. using namespace std;
  5. int Find(int x,int f[])
  6. {
  7. if(x==f[x])
  8. return x;
  9. return f[x]=Find(f[x],f);
  10. }
  11. int main()
  12. {
  13. int T;
  14. int f[1001];
  15. while(~scanf("%d",&T))
  16. {
  17. int n,k;
  18. while(T--)
  19. {
  20. scanf("%d%d",&n,&k);
  21. for(int i=1;i<=n;i++)
  22. f[i]=i;
  23. for(int i=0;i<k;i++)
  24. {
  25. int x,y;
  26. scanf("%d%d",&x,&y);
  27. x=Find(x,f);y=Find(y,f);
  28. if(x!=y)
  29. f[x]=y;
  30. }
  31. int cnt=0;
  32. //循环遍历看有多少个首领
  33. for(int i=1;i<=n;i++)
  34. if(i==f[i])
  35. cnt++;
  36. printf("%d\n",cnt);
  37. }
  38. }
  39. }

发表评论

表情:
评论列表 (有 0 条评论,251人围观)

还没有评论,来说两句吧...

相关阅读

    相关 How Many Tables

    Problem Description: 今天是伊格内修斯的生日。他邀请了很多朋友。现在是晚餐时间。伊格内修斯想知道他至少需要多少张桌子。你必须注意,并非所有的朋友都彼此认识