Last active
May 22, 2018 12:06
-
-
Save AhmetCanSolak/7f808d3f049680ede0f3675d977d29ed to your computer and use it in GitHub Desktop.
Disjoint Set implementation
This file contains 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
template<typename T> | |
class disjointset | |
{ | |
public: | |
disjointset(int n) { | |
size = n; | |
arr.reserve(n); | |
rank.reserve(n); | |
makeSet(); | |
setcount = n; | |
} | |
void makeSet() { | |
for(size_t i=0;i<size;i++){ | |
arr[i] = i; | |
rank[i] = 1; | |
} | |
} | |
T find(T a) { | |
if (arr[a]!=a) | |
arr[a] = find(arr[a]); | |
return arr[a]; | |
} | |
void unite(T a,T b) { | |
T arep = find(a); | |
T brep = find(b); | |
if (arep == brep) { | |
return; | |
} else if (rank[a] < rank[b]) { | |
arr[brep] = arep; | |
rank[arep] += rank[brep]; | |
} else if (rank[a] > rank[b]){ | |
arr[arep] = brep; | |
rank[brep] += rank[arep]; | |
} else { | |
arr[arep] = brep; | |
rank[brep] += rank[arep]; | |
} | |
} | |
T getSetSize(T a){ | |
return rank[a]; | |
} | |
private: | |
int size; | |
int setcount; | |
vector<T> arr; | |
vector<T> rank; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment