Skip to content
Snippets Groups Projects
Commit 75269967 authored by Bruno Freitas Tissei's avatar Bruno Freitas Tissei
Browse files

Improve disjoint_set

parent 80edd87b
No related branches found
No related tags found
No related merge requests found
...@@ -8,8 +8,8 @@ ...@@ -8,8 +8,8 @@
* Complexity (Space): O(n) * Complexity (Space): O(n)
*/ */
int par[MAX];
int h[MAX]; int h[MAX];
int par[MAX];
int size[MAX]; int size[MAX];
// Initialize element x // Initialize element x
...@@ -24,27 +24,24 @@ void make_set(int x) { ...@@ -24,27 +24,24 @@ void make_set(int x) {
int find_set(int x) { int find_set(int x) {
if (par[x] != x) if (par[x] != x)
par[x] = find_set(par[x]); par[x] = find_set(par[x]);
return par[x]; return par[x];
} }
// Make x and y belong to the same set // Make x and y belong to the same set
void union_set(int x, int y) { void union_set(int x, int y) {
int xroot = find_set(x); x = find_set(x);
int yroot = find_set(y); y = find_set(y);
if (xroot == yroot) if (x == y)
return; return;
if (h[xroot] < h[yroot]) { if (h[x] > h[y])
par[xroot] = yroot; swap(x, y);
size[yroot] += size[xroot];
} else {
par[yroot] = xroot;
size[xroot] += size[yroot];
if (h[xroot] == h[yroot]) par[x] = y;
h[xroot]++; size[y] += size[x];
}
if (h[x] == h[y])
h[x]++;
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment