結果

問題 No.1390 Get together
ユーザー Mitarushi
提出日時 2021-02-12 23:40:17
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 1,035 bytes
コンパイル時間 272 ms
コンパイル使用メモリ 82,556 KB
実行使用メモリ 83,588 KB
最終ジャッジ日時 2024-07-20 01:32:08
合計ジャッジ時間 7,067 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 7 WA * 22
権限があれば一括ダウンロードができます

ソースコード

diff #

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

    def get_root(self, i):
        while self.parent[i] != -1:
            i = self.parent[i]
        return i

    def is_same_tree(self, i, j):
        return self.get_root(i) == self.get_root(j)

    def merge(self, i, j):
        i = self.get_root(i)
        j = self.get_root(j)
        if i == j:
            return

        if self.rank[i] > self.rank[j]:
            self.parent[j] = i
            self.rank[i] = max(self.rank[i], self.rank[j] + 1)
            self.count[i] += self.count[j]
        else:
            self.parent[i] = j
            self.rank[j] = max(self.rank[j], self.rank[i] + 1)
            self.count[j] += self.count[i]


n, m = map(int, input().split())
col = [-1] * n
uf = UnionFind(m)
for i in range(n):
    b, c = [int(i)-1 for i in input().split()]
    if col[c] != -1:
        uf.merge(b, col[c])
    col[c] = b
ans = 0
for i in uf.count:
    ans += i-1
print(ans)
0