1. 程式人生 > >並查集與帶權並查集(轉)

並查集與帶權並查集(轉)

並查集

並查集是一個很高效演算法,理解起來也很簡單,寫起來更簡單。

①fat[i] = i;

②找到一個點的祖先

  1. int findfat(int x)  
  2. {  
  3.     if(fat[x] == x) return x;  
  4.     return findfat(fat[x]);  
  5. }  

③二中的方法肯定不好,因為如果資料比較極端,那麼並查集就退化成一個鏈了

如果加入了路徑壓縮,並查集這個演算法就更高效了。

  1. int findfat(int x)//遞迴寫法
  2. {  
  3.     if(fat[x] == x) return x;  
  4.     fat[x]=findfat(fat[x]);  
  5.     return findfat(fat[x]);  
  6. }  
  1. int findfat(int x)//非遞迴寫法 更好,因為不會RE
  2. {  
  3.     int root=x;  
  4.     while(root != fat[root])//先要找到根節點r 
  5.     {  
  6.         root=fat[root];  
  7.     }  
  8.     int y=x;  
  9.     while(y!=root)  
  10.     {  
  11.         int fath=fat[y];  
  12.         fat[y]=root;  
  13.         y=fath;  
  14.     }  
  15.     return
     r;  
  16. }  
④合併
  1. void join(int x,int y)  
  2. {  
  3.     int fatx=findfat(x),faty=findfat(y);  
  4.     if(fatx != faty)  
  5.     {  
  6.         fat[fatx]=faty;  
  7.     }  
  8. }  


帶權並查集

帶權值的並查集只不過是在並查集中加入了一個value[ ]陣列 value[ ]可以記錄很多種東西,不一定是類似距離這種東西,也可以是相對於根節點的狀態 加入了權值,函式應該有一些改變 ①找到一個點的祖先
  1. int findfat(int x)  
  2. {  
  3.     if
    (fat[x] == x) return x;  
  4.     int tmp=fat[x];  
  5.     fat[x]=findfat(fat[x]);  
  6.     //在此處修改val比如:
  7.     value[x]=value[tmp]+1;  
  8.     return fat[x];   
  9. }