並查集是一種樹型的高級數據結構,主要用於處理不相交集合的合併及查詢問題。它在計算機科學中有着廣泛的應用,例如求解最小生成樹、親戚關係的判定、確定無向圖的連通子圖個數、最小公共祖先問題等,都要用到並查集。
//集合
#include <stdio.h>
#define maxn 1000
int set[maxn]; //數組存集合
int Find(int s[], int x) //樹根用負數存-1,-2,-3...
{
while (s[x] >= 0) //數組s存放的是parent
x = s[x];
return x;
}
//判斷兩個元素是否在一個集合中:利用find 查看根
void Union(int s[], int Root1, int Root2) //此處root不是指存放負數的那個標誌位,s[root]纔是標誌位
{
s[Root1] = Root2; //root1併到root2
}
void Union2(int s[], int Root1, int Root2) //按秩合併,將總結點數存在根中並且取負,把矮樹連在高樹上面
{
if (s[Root2] < s[Root1]) //標誌位-B<-A 即B>A 所以把集合1併到集合2上
{
s[Root2] += s[Root1];
s[Root1] = Root2;
}
else
{
s[Root1] += s[Root2];
s[Root2] = Root1;
}
}
//路徑壓縮find:反覆調用原find去調用底部某個元素
int Find2(int s[], int x) //尋找根
{
if (s[x] < 0) //找到集合的根
return x;
else
{
s[x] = Find2(s, s[x]);
return s[x];
}
}
路徑壓縮遞歸的理解:每次查詢都做了優化處理