How Many Tables HDOJ

清疚 2021-12-20 23:39 300阅读 0赞

How Many Tables

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 52483 Accepted Submission(s): 26049

Problem Description

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

  典型的并查集题目,将树结构搞好以后就能得到tables

Accept

  1. // 并查集
  2. import java.util.Scanner;
  3. public class Main{
  4. static int T;
  5. static int tree[];
  6. static int n;
  7. static int m;
  8. public static int findFather(int node){
  9. if(node!=tree[node]){
  10. return tree[node]=findFather(tree[node]);
  11. }
  12. return node;
  13. }
  14. public static void main(String args[]){
  15. Scanner reader=new Scanner(System.in);
  16. T=reader.nextInt();
  17. while(T>=1){
  18. n=reader.nextInt();
  19. m=reader.nextInt();
  20. tree=new int[n+1];
  21. for(int i=1;i<=n;i++){
  22. tree[i]=i;
  23. }
  24. int max=n;
  25. for(int i=1;i<=m;i++){
  26. int one=reader.nextInt();
  27. int two=reader.nextInt();
  28. int oneFather=findFather(one);
  29. int twoFather=findFather(two);
  30. if(oneFather!=twoFather){ //父结点不同
  31. if(oneFather>twoFather){ //指向更大的结点
  32. tree[twoFather]=oneFather;
  33. }else{
  34. tree[oneFather]=twoFather;
  35. }
  36. max--;
  37. }
  38. }
  39. System.out.println(max);
  40. T--;
  41. }
  42. }
  43. }

转载于:https://www.cnblogs.com/chiweiming/p/10704065.html

发表评论

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

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

相关阅读

    相关 How Many Tables

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