結果

問題 No.2563 色ごとのグループ
ユーザー e60e256e60e256
提出日時 2023-12-02 15:49:52
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 487 ms / 2,000 ms
コード長 1,581 bytes
コンパイル時間 288 ms
コンパイル使用メモリ 81,700 KB
実行使用メモリ 130,528 KB
最終ジャッジ日時 2023-12-02 15:50:01
合計ジャッジ時間 7,724 ms
ジャッジサーバーID
(参考情報)
judge11 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 36 ms
53,460 KB
testcase_01 AC 36 ms
53,460 KB
testcase_02 AC 36 ms
53,460 KB
testcase_03 AC 35 ms
53,460 KB
testcase_04 AC 35 ms
53,460 KB
testcase_05 AC 36 ms
53,460 KB
testcase_06 AC 36 ms
53,460 KB
testcase_07 AC 36 ms
53,460 KB
testcase_08 AC 39 ms
53,460 KB
testcase_09 AC 42 ms
53,460 KB
testcase_10 AC 36 ms
53,460 KB
testcase_11 AC 38 ms
53,460 KB
testcase_12 AC 37 ms
53,460 KB
testcase_13 AC 36 ms
53,460 KB
testcase_14 AC 66 ms
71,044 KB
testcase_15 AC 66 ms
71,036 KB
testcase_16 AC 67 ms
71,036 KB
testcase_17 AC 67 ms
71,036 KB
testcase_18 AC 48 ms
64,460 KB
testcase_19 AC 71 ms
74,364 KB
testcase_20 AC 82 ms
78,476 KB
testcase_21 AC 78 ms
76,540 KB
testcase_22 AC 79 ms
76,412 KB
testcase_23 AC 85 ms
76,412 KB
testcase_24 AC 193 ms
96,448 KB
testcase_25 AC 158 ms
92,164 KB
testcase_26 AC 198 ms
100,424 KB
testcase_27 AC 195 ms
111,968 KB
testcase_28 AC 228 ms
117,320 KB
testcase_29 AC 274 ms
130,524 KB
testcase_30 AC 293 ms
130,528 KB
testcase_31 AC 285 ms
130,528 KB
testcase_32 AC 276 ms
130,524 KB
testcase_33 AC 487 ms
108,860 KB
testcase_34 AC 445 ms
108,272 KB
testcase_35 AC 432 ms
108,272 KB
testcase_36 AC 457 ms
108,860 KB
testcase_37 AC 417 ms
108,860 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

# 違う色の頂点をつなぐ辺は無視してよい。
# 閉路を作っても意味ないので無視してよい。
# 辺が同じ色同士かつ閉路を持っていない場合 UnionFindでくっつける。
# 各集合の大きさを把握しておく。
# Σ色, (UnionFindでのその色の集合の個数 - 1) 本だけ線を入れる必要がある。


class UnionFind:
    def __init__(self, size):
        self.parent = list(range(size))
        self.rank = [0] * size

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

    def union(self, x, y):
        px = self.find(x)
        py = self.find(y)

        if px == py:  # Already in the same set
            return

        # Union by rank
        if self.rank[px] > self.rank[py]:
            self.parent[py] = px
        elif self.rank[px] < self.rank[py]:
            self.parent[px] = py
        else:
            self.parent[py] = px
            self.rank[px] += 1


N, M = map(int, input().split())
C = list(map(int, input().split()))

uf = UnionFind(N)
for i in range(M):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    if (C[u] == C[v]):
        uf.union(u, v)


parents = set()
for i in range(N):
    parents.add(uf.find(i))

parentcolor = dict()
for parent in parents:
    if (not C[parent] in parentcolor):
        parentcolor[C[parent]] = 1
    else:
        parentcolor[C[parent]] += 1
        
ans = 0
for key, value in parentcolor.items():
    ans += value - 1
print(ans)
0