結果

問題 No.1293 2種類の道路
ユーザー KudeKude
提出日時 2020-11-20 22:35:30
言語 PyPy3
(7.3.13)
結果
AC  
実行時間 455 ms / 2,000 ms
コード長 1,458 bytes
コンパイル時間 1,097 ms
コンパイル使用メモリ 86,408 KB
実行使用メモリ 98,272 KB
最終ジャッジ日時 2023-09-30 19:38:50
合計ジャッジ時間 7,908 ms
ジャッジサーバーID
(参考情報)
judge12 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 76 ms
71,416 KB
testcase_01 AC 75 ms
71,000 KB
testcase_02 AC 76 ms
71,240 KB
testcase_03 AC 74 ms
71,288 KB
testcase_04 AC 73 ms
71,236 KB
testcase_05 AC 73 ms
71,108 KB
testcase_06 AC 71 ms
71,284 KB
testcase_07 AC 73 ms
71,180 KB
testcase_08 AC 75 ms
71,376 KB
testcase_09 AC 455 ms
89,612 KB
testcase_10 AC 438 ms
89,008 KB
testcase_11 AC 437 ms
89,276 KB
testcase_12 AC 439 ms
88,432 KB
testcase_13 AC 429 ms
88,304 KB
testcase_14 AC 297 ms
98,260 KB
testcase_15 AC 307 ms
98,272 KB
testcase_16 AC 375 ms
90,884 KB
testcase_17 AC 384 ms
93,232 KB
testcase_18 AC 356 ms
94,660 KB
testcase_19 AC 348 ms
97,644 KB
testcase_20 AC 341 ms
97,128 KB
testcase_21 AC 277 ms
78,680 KB
testcase_22 AC 282 ms
78,276 KB
testcase_23 AC 278 ms
78,684 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

class dsu:
    def __init__(self, n=0):
        self._n = n
        self.parent_or_size = [-1] * n
    
    def merge(self, a: int, b: int) -> int:
        x = self.leader(a)
        y = self.leader(b)
        if x == y:
            return x
        if self.parent_or_size[x] > self.parent_or_size[y]:
            x, y = y, x
        self.parent_or_size[x] += self.parent_or_size[y]
        self.parent_or_size[y] = x
        return x
    
    def same(self, a: int, b: int) -> bool:
        return self.leader(a) == self.leader(b)
    
    def leader(self, a: int) -> int:
        x = a
        while self.parent_or_size[x] >= 0:
            x = self.parent_or_size[x]
        while a != x:
            self.parent_or_size[a], a = x, self.parent_or_size[a]
        return x
    
    def size(self, a: int) -> int:
        return -self.parent_or_size[self.leader(a)]
    
    def groups(self):
        g = [[] for _ in range(self._n)]
        for i in range(self._n):
            g[self.leader(i)].append(i)
        return list(c for c in g if c)

n, d, w = map(int, input().split())
ufd = dsu(n)
ufw = dsu(n)
for _ in range(d):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    ufd.merge(a, b)
for _ in range(w):
    c, d = map(int, input().split())
    c -= 1
    d -= 1
    ufw.merge(c, d)
ans = 0
for g in ufd.groups():
    frm = len(g)
    to = sum(ufw.size(v) for v in set(ufw.leader(u) for u in g))
    ans += frm * to
ans -= n
print(ans)
0