HDU 1213

How Many Tables

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


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
 
Author
Ignatius.L
 
Source
 
Recommend
Eddy   |   We have carefully selected several similar problems for you:  1272 1232 1856 1325 1233 
 
Solution :并查集
自己写了一个非并查集的
WA了
初始化
Over
自己总是想到数据结构
乱七八糟
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 const int MAX=1001;
 5 int fa[MAX];
 6 int n;
 7 int m;
 8 using namespace std;
 9 void init()
10 {
11     int i;
12     for(i=0;i<=n;++i)
13     fa[i]=i;
14 }
15 int find_father(int x)
16 {
17     while(x!=fa[x])
18     {
19         x=fa[x];
20     }
21     return x;
22 }
23 void join_tree(int x,int y)
24 {
25     int a,b;
26     a=find_father(x);
27     b=find_father(y);
28     if(a!=b)
29     fa[a]=b;
30 }
31 int main()
32 {
33     int t,m,a,b,i,sum;
34     cin>>t;
35     while(t--)
36     {
37         cin>>n>>m;
38         sum=0;
39         init();
40         while(m--)
41         {
42             cin>>a>>b;
43             join_tree(a,b);
44         }
45         for(i=1;i<=n;i++)
46         if(fa[i]==i)//如果他的父亲是自己则桌子加一
47         sum+=1;
48         cout<<sum<<endl;
49     }
50     return 0;
51 }
原文地址:https://www.cnblogs.com/Run-dream/p/3865609.html