結果

問題 No.1390 Get together
ユーザー とりゐ
提出日時 2022-05-28 16:32:07
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 431 ms / 2,000 ms
コード長 962 bytes
コンパイル時間 223 ms
コンパイル使用メモリ 81,936 KB
実行使用メモリ 112,656 KB
最終ジャッジ日時 2024-09-20 22:32:29
合計ジャッジ時間 10,238 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 29
権限があれば一括ダウンロードができます

ソースコード

diff #

#UnionFind
from collections import defaultdict

class UnionFind():
    def __init__(self, n):
        self.n = 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

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

n,m=map(int,input().split())
uf=UnionFind(m+1)
color=[[] for i in range(n+1)]
for _ in range(n):
  b,c=map(int,input().split())
  color[c].append(b)

for i in range(n+1):
  for j in color[i][1:]:
    uf.union(color[i][0],j)

ans=0
for i in uf.roots():
  ans+=-uf.parents[i]-1

print(ans)
0