算法復習之並查集
阿新 • • 發佈:2018-09-29
max return 查詢 合並 clas 直接 結構 壓縮 構建
並查集是一種以樹結構建立的能夠高效處理分組問題中合並,查找操作的數據結構
支持三種基本操作:建立,查詢,合並
實現:
1 #include<iostream> 2 using namespace std; 3 const int maxn=10000; 4 int a[maxn],heigh[maxn],par[maxn]; 5 void init(int n) 6 { 7 for(int i=0;i<n;i++) 8 { 9 par[i]=i; 10 heigh[i]=1; 11 } 12 }13 int findPar(int x) 14 { 15 if(x==par[x]) 16 return x; 17 //遞歸求父親,並直接連向根,路徑壓縮 18 else 19 return par[x]=fin(par[x]); 20 } 21 void connect(int x,int y) 22 { 23 x=findPar(x); 24 y=findPar(y); 25 if(x==y) 26 return ; 27 //如果父親不相等,比較高度,合並 28 if(heigh[x]<heigh[y])29 { 30 par[x]=y; 31 } 32 else{ 33 par[y]=x; 34 if(heigh[x]==heigh[y]) 35 heigh[x]++; 36 } 37 }
算法復習之並查集