Created
May 13, 2018 05:50
-
-
Save private-yusuke/2743e280f618abfbdc3fe939b63137c0 to your computer and use it in GitHub Desktop.
Union Find木のD言語の実装
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
class UnionFind(T) { | |
T[] arr; | |
this(ulong n) { | |
arr.length = n+1; | |
arr[] = -1; | |
} | |
T root(T x) { | |
return arr[x] < 0 ? x : root(arr[x]); | |
} | |
bool same(T x, T y) { | |
return root(x) == root(y); | |
} | |
bool unite(T x, T y) { | |
x = root(x); | |
y = root(y); | |
if(x == y) return false; | |
if(arr[x] > arr[y]) swap(x, y); | |
arr[x] += arr[y]; | |
arr[y] = x; | |
return true; | |
} | |
T size(T a) { | |
return -arr[root(a)]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment