結果

問題 No.1390 Get together
ユーザー kohei2019kohei2019
提出日時 2021-02-12 21:37:30
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 437 ms / 2,000 ms
コード長 1,621 bytes
コンパイル時間 682 ms
コンパイル使用メモリ 86,712 KB
実行使用メモリ 98,772 KB
最終ジャッジ日時 2023-09-27 03:15:50
合計ジャッジ時間 11,062 ms
ジャッジサーバーID
(参考情報)
judge15 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 70 ms
71,452 KB
testcase_01 AC 69 ms
71,176 KB
testcase_02 AC 68 ms
71,344 KB
testcase_03 AC 115 ms
78,248 KB
testcase_04 AC 110 ms
78,348 KB
testcase_05 AC 118 ms
78,068 KB
testcase_06 AC 119 ms
77,884 KB
testcase_07 AC 108 ms
77,800 KB
testcase_08 AC 111 ms
78,136 KB
testcase_09 AC 113 ms
78,148 KB
testcase_10 AC 68 ms
71,432 KB
testcase_11 AC 65 ms
71,280 KB
testcase_12 AC 67 ms
71,348 KB
testcase_13 AC 67 ms
71,324 KB
testcase_14 AC 69 ms
71,564 KB
testcase_15 AC 66 ms
71,276 KB
testcase_16 AC 219 ms
94,076 KB
testcase_17 AC 303 ms
96,404 KB
testcase_18 AC 211 ms
94,072 KB
testcase_19 AC 411 ms
97,772 KB
testcase_20 AC 395 ms
98,068 KB
testcase_21 AC 420 ms
98,764 KB
testcase_22 AC 339 ms
96,732 KB
testcase_23 AC 352 ms
97,204 KB
testcase_24 AC 353 ms
97,696 KB
testcase_25 AC 429 ms
98,344 KB
testcase_26 AC 429 ms
97,980 KB
testcase_27 AC 416 ms
98,772 KB
testcase_28 AC 422 ms
97,568 KB
testcase_29 AC 401 ms
97,540 KB
testcase_30 AC 437 ms
98,424 KB
testcase_31 AC 431 ms
98,052 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#unionfind経路圧縮あり
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = list(range(n))

    def find(self, x):
        if self.parents[x] == x:
            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 self.parents[x] > self.parents[y]:
            x, y = y, x
            
        if x == y:
            return

        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

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

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

N,M = map(int,input().split())
lsN = [[] for i in range(N)]
for i in range(N):
    b,c = map(int,input().split())
    b -= 1
    c -= 1
    lsN[c].append(b)
#合わせるunionfind,unionした回数
UF = UnionFind(M)
ans = 0
for i in range(N):
    if len(lsN[i]) <= 1:
        continue
    
    for j in range(len(lsN[i])-1):
        if UF.find(lsN[i][j]) == UF.find(lsN[i][j+1]):
            continue
        ans += 1
        UF.union(lsN[i][j],lsN[i][j+1])
print(ans)
0