from AtCoder Library Practice Contest ACLPC_A A - Disjoint Set Union いわゆるUnionFind 木を作ることで効率的に辺の追加と連結かどうかの判断ができる