HDOJ1213 How Many Tables[并查集入门]

How Many Tables

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


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
 
 
 
 
 
 
并查集第一题,所以找了道简单的来做,关键还是要写好那几个函数,认清自己所构建的树的结构。
code:
 1 #include <iostream>   
 2 #include <iomanip>   
 3 #include <fstream>   
 4 #include <sstream>   
 5 #include <algorithm>   
 6 #include <string>   
 7 #include <set>   
 8 #include <utility>   
 9 #include <queue>   
10 #include <stack>   
11 #include <list>   
12 #include <vector>   
13 #include <cstdio>   
14 #include <cstdlib>   
15 #include <cstring>   
16 #include <cmath>   
17 #include <ctime>   
18 #include <ctype.h> 
19 using namespace std;
20 
21 #define MAXN 1005
22 
23 int father[MAXN];
24 int t,n,m;
25 int a,b;
26 int cnt;
27 
28 int getfather(int v)
29 {
30     if(father[v]!=v)
31         father[v]=getfather(father[v]);
32     return father[v];
33 }
34 
35 void Union(int x,int y)
36 {
37     x=getfather(x);
38     y=getfather(y);
39     if(x!=y)
40         father[x]=y;
41 }
42 
43 int main()
44 {
45     int i;
46     while(~scanf("%d",&t))
47     {
48         while(t--)
49         {
50             cnt=0;
51             scanf("%d%d",&n,&m);
52             for(i=1;i<=n;i++)
53                 father[i]=i;
54             for(i=1;i<=m;i++)
55             {
56                 scanf("%d%d",&a,&b);
57                 Union(a,b);
58             }
59             for(i=1;i<=n;i++)
60                 if(father[i]==i)
61                     cnt++;
62             printf("%d\n",cnt);
63         }
64     }
65     return 0;
66 }
原文地址:https://www.cnblogs.com/XBWer/p/2616974.html