并查集是一种树型的数据结构,用于处理一些不相交集合(Disjoint Sets)的合并及查询问题。常常在使用中以森林来表示。
主要操作:
初始化:把每个点所在集合初始化为其自身。通常来说,这个步骤在每次使用该数据结构时只需要执行一次,无论何种实现方式,时间复杂度均为O(N)。
查找:查找元素所在的集合,即根节点。
合并:将两个元素所在的集合合并为一个集合。通常来说,合并之前,应先判断两个元素是否属于同一集合,这可用上面的“查找”操作实现。
hdu1232:http://acm.hdu.edu.cn/showproblem.php?pid=1232
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
void init(int a[], int n)
{
for (int i=1; i<=n; ++i)
a[i] = -1;
}
int find(int a[], int x)
{
int t = x;
while (a[t]>=0)//查找祖先t
t = a[t];
while (a[x]>=0)//路径压缩
{
int j = x;
x = a[x];
a[j] = t;
}
return t;
}
void merge(int a[], int x, int y)
{
x = find(a, x);
y = find(a, y);
if (x==y)//祖先相同返回
return;
if (a[x]>=a[y])//数量少的合并到数量多的上面(此时a[x]a[y]均为负,负的程度代表有多少个结点)
{
a[y] += a[x];
a[x] = y;
}
else if (a[x]<a[y])
{
a[x] += a[y];
a[y] = x;
}
}
int main()
{
int a[1005], n, m, s, e, cnt;
while (~scanf("%d", &n))
{
if (n==0)
break;
scanf("%d", &m);
init(a, n);
for (int i=0; i<m; ++i)
{
scanf("%d%d", &s, &e);
merge(a, s, e);
}
cnt = 0;
for (int i=1; i<=n; ++i)
if (a[i]<0)
cnt ++;
printf("%d\n", cnt-1);
}
return 0;
}