ABC177 D - Friends
備忘録
問題
回答
import sys, os, math, bisect, itertools, collections, heapq, queue, copy, array # from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall # from decimal import Decimal # from collections import defaultdict, deque sys.setrecursionlimit(10000000) ii = lambda: int(sys.stdin.buffer.readline().rstrip()) il = lambda: list(map(int, sys.stdin.buffer.readline().split())) fl = lambda: list(map(float, sys.stdin.buffer.readline().split())) iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)] iss = lambda: sys.stdin.buffer.readline().decode().rstrip() sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split())) isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)] lcm = lambda x, y: (x * y) // math.gcd(x, y) MOD = 10 ** 9 + 7 INF = float('inf') class UnionFind: def __init__(self, N): self.tree = [-1 for _ in range(N)] def root(self, N): if self.tree[N] < 0: return N self.tree[N] = self.root(self.tree[N]) return self.tree[N] def same(self, x, y): return self.root(x) == self.root(y) def unite(self, x, y): x = self.root(x) y = self.root(y) if x == y: return if self.tree[x] > self.tree[y]: x, y = y, x self.tree[x] += self.tree[y] self.tree[y] = x def size(self, x): return -self.tree[self.root(x)] def main(): if os.getenv("LOCAL"): sys.stdin = open("input.txt", "r") N, M = il() uf = UnionFind(N) for _ in range(M): a, b = il() a -= 1 b -= 1 uf.unite(a, b) ret = 0 for n in range(N): ret = max(ret, uf.size(n)) print(ret) if __name__ == '__main__': main()
考え方
友達関係をグラフに置き換えて考える。
同じ連結成分に存在する頂点は、全て別のグループに属する必要がある。
そのため、最も大きい連結成分の頂点数が回答となる。
(小さい連結成分の各頂点は大きいほうの連結成分で作られるグループに属することが可能なため)
回答は普段使用しているUnionFind木の実装に、
各連結成分の連結している頂点の数を求める関数(def size(self, x):
)を追加して行った。
実装は、UnionFind木を作るときに、各頂点がどのルートに属するかを管理する配列を、
-1
で初期化しておき、
頂点を連結するときに、親となる頂点に対して、子の頂点が持つ子の数を加算することで
親の頂点が子の数を保持している。
参考はchokudai氏の公式解説