并查集,并查集是一种树形结构,又叫“不相交集合”,保持了一组不相交的动态集合,每个集合通过一个代表来识别,代表即集合中的某个成员,通常选择根做这个代表。
也就是说,并查集是用来处理不相交集合类型问题,如问不相交集合有几个。给定节点,找到该节点所在集合元素个数,当然这只是水题。并查集会与其他算法结合着考,如LCA中的tarjian算法。后续博客会整理。
并查集,顾名思义,主要分三部分。
一:合并:给出两点关系,如果属于同一集合,进行merge
二:查:在合并时,需要先写出查,即找到该点的祖先点
三:集:merge后,将新加入的点的祖先点更新
然后,点集就因为共同的祖先点被分为不同的集合啦
结合例题更容易理解
hdu1232畅通工程
畅通工程
某省调查城镇交通状况,得到现有城镇道路统计表,表中列出了每条道路直接连通的城镇。省政府“畅通工程”的目标是使全省任何两个城镇间都可以实现交通(但不一定有直接的道路相连,只要互相间接通过道路可达即可)。问最少还需要建设多少条道路?
Input
测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是城镇数目N ( < 1000 )和道路数目M;随后的M行对应M条道路,每行给出一对正整数,分别是该条道路直接连通的两个城镇的编号。为简单起见,城镇从1到N编号。
注意:两个城市之间可以有多条道路相通,也就是说
3 3
1 2
1 2
2 1
这种输入也是合法的
当N为0时,输入结束,该用例不被处理。
Output
对每个测试用例,在1行里输出最少还需要建设的道路数目。
Sample Input
4 2
1 3
4 3
3 3
1 2
1 3
2 3
5 2
1 2
3 5
999 0
0
Sample Output
1
0
2
998
就是说将所有独立的集合连接起来还需要几条路,那只要找到独立集合个数-1就可以啦
#include<stdio.h>
int father[1005];
int Find(int x)
{
while(x!=father[x])
x=father[x];
return x;
}
void Combine(int a,int b)
{
int fa=Find(a);
int fb=Find(b);
if(fa!=fb)
{
father[fa]=fb;
}
}
int main()
{
int n,m;
int i;
int a,b;
while(~scanf("%d",&n))
{
if(n==0)
break;
scanf("%d",&m);
int sum=0;
for(i=1;i<=n;i++)
father[i]=i;
for(i=0;i<m;i++)
{
scanf("%d%d",&a,&b);
Combine(a,b);
}
for(i=1;i<=n;i++)
{
if(father[i]==i)
sum++;
}
printf("%d\n",sum-1);
}
return 0;
}
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int pre[1010]; //里面全是掌门
int unionsearch(int root)
{
int son, tmp;
son = root;
while(root != pre[root]) //寻找掌门ing……
root = pre[root];
while(son != root) //路径压缩
{
tmp = pre[son];
pre[son] = root;
son = tmp;
}
return root; //掌门驾到~
}
int main()
{
int num, road, total, i, start, end, root1, root2;
while(scanf("%d%d", &num, &road) && num)
{
total = num - 1; //共num-1个门派
for(i = 1; i <= num; ++i) //每条路都是掌门
pre[i] = i;
while(road--)
{
scanf("%d%d", &start, &end); //他俩要结拜
root1 = unionsearch(start);
root2 = unionsearch(end);
if(root1 != root2) //掌门不同?踢馆!~
{
pre[root1] = root2;
total--; //门派少一个,敌人(要建的路)就少一个
}
}
printf("%d\n", total);//天下局势:还剩几个门派
}
return 0;
}