elements that are same group with i
i がグループのリーダーか返す. 各グループにはただ1つのみリーダーが存在する
merge a, b
Are a and b same group?
group count
1 import std.algorithm : equal, sort; 2 auto uf = UnionFind(5); 3 assert(!uf.same(1, 3)); 4 assert(uf.same(0, 0)); 5 6 uf.merge(3, 2); 7 uf.merge(1, 1); 8 uf.merge(4, 2); 9 uf.merge(4, 3); 10 11 assert(uf.count == 3); 12 assert(uf.id[2] == uf.id[3]); 13 assert(uf.id[2] == uf.id[4]); 14 assert(equal(uf.group(0), [0])); 15 assert(equal(uf.group(1), [1])); 16 assert(equal(sort(uf.group(2).dup), [2, 3, 4])); 17 18 auto cnt = 0; 19 foreach (i; 0..5) { 20 if (!uf.isLeader(i)) continue; 21 cnt += uf.group(i).length; 22 } 23 assert(cnt == 5); // view all element exactly once
UnionFind (Disjoint Set Union)