How Many Tables(并查集)

http://acm.hdu.edu.cn/showproblem.php?pid=1213

How Many Tables

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


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
 

 题解:简单的并查集,

并查集,最基本的操作就是1,查,2,并,

  要有一个储存父亲节点的数组F[N] ,开始全部标记成-1 ,表示没有父亲

  1.查: 如果这个节点的父亲数组是-1 说明没有父亲就返回他本身,反之则接着查找他父亲的父亲,为了不重复查询,所以在查询的过程,直接将这个点的父亲更新到所找到的父亲的父亲。。。

  2.并: 找到这两个点的父亲,如果这两个点的父亲不是同一个值,将其中一个点的祖宗(最上面的点)的父亲标记成另一个点

下面是代码:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 using namespace std;
 5 #define N 1010
 6 int F[N];
 7 int Gf(int t)
 8 {
 9     if(F[t]==-1) return t;
10     F[t] = Gf(F[t]);
11     return F[t];
12 }
13 void bing (int a , int b)
14 {
15     int fa = Gf(a);
16     int fb = Gf(b);
17     if(fa!=fb) F[fb] = fa;
18 }
19 int main()
20 {
21     int T;
22     scanf("%d",&T);
23     while(T--)
24     {
25         int n , m;
26         scanf("%d%d",&n,&m);
27         int a , b;
28         memset(F,-1,sizeof(F));
29         for(int i = 0 ;i < m ;i++)
30         {
31             scanf("%d%d",&a,&b);
32             bing(a,b);
33         }
34         int res = 0;
35         for(int i = 1 ; i <= n ; i++)
36         {
37             if(F[i]==-1) res++;
38         }
39         printf("%d
",res);
40         //if(T!=0) puts("");
41     }
42     return 0 ;
43 }
原文地址:https://www.cnblogs.com/shanyr/p/4689345.html