並查集與帶權並查集(轉)
阿新 • • 發佈:2019-01-26
並查集
並查集是一個很高效演算法,理解起來也很簡單,寫起來更簡單。
①fat[i] = i;
②找到一個點的祖先
- int findfat(int x)
- {
- if(fat[x] == x) return x;
- return findfat(fat[x]);
- }
③二中的方法肯定不好,因為如果資料比較極端,那麼並查集就退化成一個鏈了
如果加入了路徑壓縮,並查集這個演算法就更高效了。
- int findfat(int x)//遞迴寫法
- {
- if(fat[x] == x) return x;
-
fat[x]=findfat(fat[x]);
- return findfat(fat[x]);
- }
- int findfat(int x)//非遞迴寫法 更好,因為不會RE
- {
- int root=x;
- while(root != fat[root])//先要找到根節點r
- {
- root=fat[root];
- }
- int y=x;
- while(y!=root)
- {
- int fath=fat[y];
- fat[y]=root;
- y=fath;
- }
-
return
- }
- void join(int x,int y)
- {
- int fatx=findfat(x),faty=findfat(y);
- if(fatx != faty)
- {
- fat[fatx]=faty;
- }
- }
帶權並查集
帶權值的並查集只不過是在並查集中加入了一個value[ ]陣列 value[ ]可以記錄很多種東西,不一定是類似距離這種東西,也可以是相對於根節點的狀態 加入了權值,函式應該有一些改變 ①找到一個點的祖先- int findfat(int x)
- {
-
if
- int tmp=fat[x];
- fat[x]=findfat(fat[x]);
- //在此處修改val比如:
- value[x]=value[tmp]+1;
- return fat[x];
- }