結果

問題 No.2563 色ごとのグループ
ユーザー MM
提出日時 2023-12-02 17:34:14
言語 Python3
(3.13.1 + numpy 2.2.1 + scipy 1.14.1)
結果
AC  
実行時間 1,213 ms / 2,000 ms
コード長 941 bytes
コンパイル時間 264 ms
コンパイル使用メモリ 12,544 KB
実行使用メモリ 36,464 KB
最終ジャッジ日時 2024-09-26 21:15:32
合計ジャッジ時間 14,862 ms
ジャッジサーバーID
(参考情報)
judge5 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 35
権限があれば一括ダウンロードができます

ソースコード

diff #

class UnionFind:
    def __init__(self, size):
        self.parent = [i for i in range(size)]

    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]

    def merge(self, x, y):
        x_root = self.find(x)
        y_root = self.find(y)
        if x_root != y_root:
            self.parent[x_root] = y_root

    def leader(self, x):
        return self.find(x)


# Read N and M
N, M = map(int, input().split())

# Read C
C = list(map(int, input().split()))

# Initialize UnionFind
uf = UnionFind(N)

# Process the edges
for _ in range(M):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    if C[u] == C[v]:
        uf.merge(u, v)

# Count the groups
mp = {}
for i in range(N):
    leader = uf.leader(i)
    if leader == i:
        mp[C[i]] = mp.get(C[i], 0) + 1

# Calculate the answer
ans = sum(value - 1 for value in mp.values())
print(ans)
0