杭电1213题解:一道最基础的并查集问题

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
 
 
根据题意我们可以知道,这是一道并查集的基础问题,不涉及路径也不涉及连通分量内部元素的关系,只求连通分量的个数,由于本题数据并不是很大,我们可以简单地使用Quick-Union算法即可(甚至Quick-Find算法也可)
根据Quick-Union算法,令每次输入的两个元素所在的树根相等,即id[tree(mi)] = id[tree(mj)]  (tree函数是索引目标元素树根的函数), 最后统计树根的个数(即id[x] = x)
 
下面看代码
 1 #include <iostream>
 2 #include <cstring>
 3 
 4 using namespace std;
 5 int id[1005];
 6 int tree(int x)
 7 {
 8     while(id[x]!=x)
 9     {
10         x = id[x];
11     }
12     return id[x];
13 }
14 
15 int main()
16 {
17     int T;
18     int i = 0, j = 0;
19     int n, m;
20 
21     int mi, mj;
22     int counts;
23     cin >> T;
24     for(i=0; i<T; i++)
25     {
26         counts = 0;
27         memset(id, 0, sizeof(id));
28         cin >> n >> m;
29         for(j=0; j<=n; j++){
30             id[j] = j;
31         }
32         for(j=1; j<=m; j++)
33         {
34             cin >> mi >> mj;
35             id[tree(mi)] = id[tree(mj)];
36         }
37         for(j=1; j<=n; j++)
38         {
39             if(id[j]==j)
40                counts++;
41         }
42 
43         cout << counts << endl;
44     }
45     return 0;
46 }

 

posted @ 2017-03-08 20:05  明早六点起  阅读(254)  评论(0编辑  收藏  举报