結果
問題 | No.2563 色ごとのグループ |
ユーザー |
![]() |
提出日時 | 2023-12-02 15:34:00 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 355 ms / 2,000 ms |
コード長 | 1,809 bytes |
コンパイル時間 | 195 ms |
コンパイル使用メモリ | 82,520 KB |
実行使用メモリ | 111,488 KB |
最終ジャッジ日時 | 2024-09-26 18:54:22 |
合計ジャッジ時間 | 6,131 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 35 |
ソースコード
""" 考察 色違いの場合、辺はないと考えて良さそう 色ごとのグループ数 - 1 の和が答え 色ごとの頂点数を数えておく 辺を結ぶたびに、その色の頂点数を1減らす """ # from my.union_find import UnionFind class UnionFind: def __init__(self, n: int) -> None: self.parents = [-1] * n self.data = [0] * n self.n = n def root(self, x: int) -> int: if self.parents[x] < 0: return x self.parents[x] = self.root(self.parents[x]) return self.parents[x] def unite(self, x: int, y: int) -> None: x = self.root(x) y = self.root(y) if x == y: return if self.parents[x] > self.parents[y]: x, y = y, x self.parents[x] += self.parents[y] self.parents[y] = x def size(self, x: int) -> int: return -self.parents[self.root(x)] def roots(self) -> list[int]: return [i for i, x in enumerate(self.parents) if x < 0] def same(self, x, y) -> bool: return self.root(x) == self.root(y) def groups(self) -> dict[int, list[int]]: group_members = {} for member in range(self.n): p = self.root(member) if not p in group_members: group_members[p] = [] group_members[p].append(member) return group_members N, M = map(int, input().split()) C = list(map(lambda x:int(x)-1, input().split())) cnt = [0] * N for c in C: cnt[c] += 1 uf = UnionFind(N) for _ in range(M): a, b = map(int, input().split()) a -= 1; b -= 1 if C[a] == C[b]: if uf.same(a, b): continue else: uf.unite(a, b) cnt[C[a]] -= 1 ans = sum(c - 1 for c in cnt if c > 0) print(ans)