Skip to content

Instantly share code, notes, and snippets.

@private-yusuke
Created May 13, 2018 05:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save private-yusuke/2743e280f618abfbdc3fe939b63137c0 to your computer and use it in GitHub Desktop.
Save private-yusuke/2743e280f618abfbdc3fe939b63137c0 to your computer and use it in GitHub Desktop.
Union Find木のD言語の実装
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