#include<bits/stdc++.h>
using namespace std;
#define NumSize 100
#ifndef DisjSet_DisjSet_h
#define DisjSet_DisjSet_h
const int NumSets = 10;
/*
* Disjoint Set 不相交集 / 并查集
* 主要操作为:查找和合并
*/
typedef int DisjSet[NumSets + 1]; // 为了下标对齐,这里设定数组大小为NumSets + 1,第0个元素起占位作用
typedef int SetType; // 父节点保存的元素的类型
typedef int ElementType;
void Intialize(DisjSet S) ;
void SetUnion(DisjSet S,SetType Root1,SetType Root2) ;
SetType Find(ElementType X,DisjSet S) ;
#endif
void Intialize(DisjSet S)
{
int i ;
for(i = NumSets; i > 0;i--)
S[i] = 0 ;
}
SetType Find(ElementType X,DisjSet S)
{
if(S[X] <= 0)
return X ;
else
return S[X] = Find(S[X],S) ;
}
void SetUnion(DisjSet S,SetType Root1,SetType Root2)//S[根节点]==树的高度的相反数
{
Root1=Find(Root1,S);
Root2=Find(Root2,S);
if(S[Root2] < S[Root1]) //R2高
S[Root1] = Root2 ;
else
{
if(S[Root1] == S[Root2])
S[Root1]-- ;
S[Root2] = Root1 ;
}
}
int main()
{
system("pause");
return 0;
}
数据结构——不相交集(并查集)
最新推荐文章于 2024-07-09 17:14:48 发布