并查集专题

并查集专题

 

 1 struct UF {  2 int rt[MAXN];  3 void init(void) {  4 memset (rt, -1, sizeof (rt));  5  }  6 int Find(int x) {  7 return rt[x] == -1 ? x : rt[x] = Find (rt[x]);  8  }  9 void Union(int x, int y) { 10 x = Find (x); y = Find (y); 11 if (x == y) return ; 12 rt[x] = y; 13  } 14 bool same(int x, int y) { 15 return Find (x) == Find (y); 16  } 17 }uf;
1 int Find(int x) { 2 int p = x; 3 while (rt[x] != -1) x = rt[x]; 4 while (p != x) { 5 int t = rt[p]; rt[p] = x; p = t; 6  } 7 }
代形式的路径压缩
1 void Union(int x, int y) { 2 x = Find (x); y = Find (y); 3 if (x == y) return ; 4 if (rk[x] > rk[y]) rt[y] = x; 5 else { 6 rt[x] = y; 7 if (rk[x] == rk[y]) rk[y]++; 8  } 9 }
按秩合并

 

你可能感兴趣的:(并查集)