Created
August 11, 2013 13:48
-
-
Save airekans/6204978 to your computer and use it in GitHub Desktop.
Union Find Set(并查集):
基本操作(优势):1. 查找某个元素所在的集合; 2. 合并两个不相交的集合。 目前看到比较多的实现都是基于数组的。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Union Find Set | |
const int MAXN = 100; | |
int father[MAXN] = {0}; | |
int rank[MAXN] = {0}; | |
int find_set(const int x) | |
{ | |
if (father[x] != x) | |
{ | |
father[x] = find_set(father[x]); | |
} | |
return father[x]; | |
} | |
void union(const int x, const int y) | |
{ | |
const int fx = find_set(x); | |
const int fy = find_set(y); | |
if (fx == fy) | |
{ | |
return; | |
} | |
else if (rank[fx] < rank[fy]) | |
{ | |
father[fx] = fy; | |
++rank[fy]; | |
} | |
else | |
{ | |
father[fy] = fx; | |
++rank[fx]; | |
} | |
} | |
bool is_in_same_set(const int x, const int y) | |
{ | |
return find_set(x) == find_set(y); | |
} | |
int main() | |
{ | |
for (int i = 0; i < MAXN; ++i) | |
{ | |
father[i] = i; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment