A

并查集是一个找爸爸的过程。

  通过finds来查找某一值的父亲

  通过unions来联合两数字之间的联系。

下边给出一实例来解释

题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1232

以下为代码

 1 #include<stdio.h>
 2 #include<string.h>
 3 #define MAX_N 1050
 4 int pre[MAX_N];
 5 int finds(int x)
 6 {
 7     return  x==pre[x]?x:finds(pre[x]);
 8 }
 9 void unions(int x, int y)
10 {
11     int u=finds(x);
12     int v=finds(y);
13     if(u==v)
14         return;
15     pre[u]=v;
16 }
17 int main()
18 {
19     int n,m,ans;
20     while(scanf("%d",&n)!=EOF&&n)
21     {
22         memset(pre,0,sizeof(pre));
23         for(int i=1; i<=n; i++)
24         {
25             pre[i]=i;
26         }
27         scanf("%d",&m);
28         for(int j=0; j<m; j++)
29         {
30             int u,v;
31             scanf("%d%d",&u,&v);
32             unions(u,v);
33         }
34         ans=-1;
35         for(int i=1; i<=n; i++)
36         {
37             if(pre[i]==i)
38                 ans++;
39         }
40         printf("%d
",ans);
41     }
42 }
原文地址:https://www.cnblogs.com/Yinchen-One/p/8540721.html