結果

問題 No.1390 Get together
ユーザー paruf4paruf4
提出日時 2021-02-12 23:01:51
言語 PyPy3
(7.3.13)
結果
AC  
実行時間 520 ms / 2,000 ms
コード長 1,529 bytes
コンパイル時間 273 ms
コンパイル使用メモリ 87,272 KB
実行使用メモリ 134,064 KB
最終ジャッジ日時 2023-09-27 06:12:37
合計ジャッジ時間 10,744 ms
ジャッジサーバーID
(参考情報)
judge14 / judge12
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 65 ms
71,448 KB
testcase_01 AC 67 ms
71,180 KB
testcase_02 AC 67 ms
71,432 KB
testcase_03 AC 113 ms
78,888 KB
testcase_04 AC 115 ms
78,708 KB
testcase_05 AC 119 ms
78,968 KB
testcase_06 AC 117 ms
78,712 KB
testcase_07 AC 113 ms
78,668 KB
testcase_08 AC 110 ms
78,664 KB
testcase_09 AC 119 ms
79,132 KB
testcase_10 AC 67 ms
71,432 KB
testcase_11 AC 67 ms
71,360 KB
testcase_12 AC 68 ms
71,428 KB
testcase_13 AC 67 ms
71,384 KB
testcase_14 AC 66 ms
71,456 KB
testcase_15 AC 66 ms
71,184 KB
testcase_16 AC 270 ms
104,436 KB
testcase_17 AC 384 ms
126,100 KB
testcase_18 AC 269 ms
113,900 KB
testcase_19 AC 501 ms
133,680 KB
testcase_20 AC 500 ms
133,328 KB
testcase_21 AC 520 ms
134,064 KB
testcase_22 AC 409 ms
127,900 KB
testcase_23 AC 423 ms
128,024 KB
testcase_24 AC 413 ms
128,076 KB
testcase_25 AC 505 ms
134,052 KB
testcase_26 AC 501 ms
133,616 KB
testcase_27 AC 501 ms
133,652 KB
testcase_28 AC 486 ms
132,576 KB
testcase_29 AC 486 ms
133,508 KB
testcase_30 AC 485 ms
133,172 KB
testcase_31 AC 492 ms
133,020 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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 same(self, x, y):
        return self.find(x) == self.find(y)

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

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

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

    def groups(self):
        roots = self.roots()
        r_to_g = {}
        for i, r in enumerate(roots):
            r_to_g[r] = i
        groups = [[] for _ in roots]
        for i in range(self.n):
            groups[r_to_g[self.find(i)]].append(i)
        return groups


n, m = map(int, input().split())

G = [set() for _ in range(n)]
for i in range(n):
    b, c = map(int, input().split())
    b -= 1
    c -= 1
    G[c].add(b)

uf = UnionFind(m)
G = [list(g) for g in G]
res = 0
for g in G:
    for i in range(len(g)-1):
        if uf.same(g[i],g[i+1]):
            continue
        uf.union(g[i],g[i+1])
        res += 1

print(res)
0