結果

問題 No.2563 色ごとのグループ
ユーザー tetz
提出日時 2023-12-02 16:16:17
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 450 ms / 2,000 ms
コード長 933 bytes
コンパイル時間 208 ms
コンパイル使用メモリ 81,880 KB
実行使用メモリ 113,420 KB
最終ジャッジ日時 2024-09-26 20:04:03
合計ジャッジ時間 7,838 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 35
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict as dd


class UnionFind:
    def __init__(self, n):
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(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


N, M = map(int, input().split())
c = list(map(int, input().split()))
gc = dd(lambda: -1)
for ci in c:
    gc[ci] += 1
uf = UnionFind(N)
for _ in range(M):
    u, v = map(lambda x: int(x) - 1, input().split())
    if c[u] == c[v] and uf.find(u) != uf.find(v):
        uf.union(u, v)
        gc[c[u]] -= 1
# print(sum(gc.values()) - len(gc.keys()))
print(sum(gc.values()))
0