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

Add disjoint_set

parent 998db525
No related branches found
No related tags found
No related merge requests found
/**
* Disjoint-set
*
* Complexity (Time): O(1)
* makeset -> O(1)
* find -> O(a(n))
* union_set -> O(a(n))
* Complexity (Space): O(n)
*/
int par[MAX];
int rank[MAX];
int sz[MAX];
// Initialize element x
void makeset(int x) {
par[x] = x;
rank[x] = 0;
sz[x] = 1;
}
// Return set index from element x
int find(int x) {
if (par[x] != x)
par[x] = find(par[x]);
return par[x];
}
// Make x and y belong to the same set
void union_set(int x, int y) {
int xroot = find(x);
int yroot = find(y);
if (xroot == yroot)
return;
if (rank[xroot] < rank[yroot]) {
par[xroot] = yroot;
sz[yroot] += sz[xroot];
} else if (rank[xroot] > rank[yroot]) {
par[yroot] = xroot;
sz[xroot] += sz[yroot];
} else {
par[yroot] = xroot;
sz[xroot] += sz[yroot];
rank[xroot]++;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment