結果

問題 No.1293 2種類の道路
ユーザー KudeKude
提出日時 2020-11-20 22:35:30
言語 PyPy3
(7.3.8)
結果
AC  
実行時間 539 ms / 2,000 ms
コード長 1,458 bytes
コンパイル時間 239 ms
使用メモリ 103,628 KB
最終ジャッジ日時 2023-02-23 19:07:09
合計ジャッジ時間 9,323 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
使用メモリ
testcase_00 AC 78 ms
75,752 KB
testcase_01 AC 78 ms
75,500 KB
testcase_02 AC 76 ms
75,672 KB
testcase_03 AC 78 ms
75,736 KB
testcase_04 AC 80 ms
75,736 KB
testcase_05 AC 77 ms
75,844 KB
testcase_06 AC 78 ms
75,756 KB
testcase_07 AC 77 ms
75,752 KB
testcase_08 AC 79 ms
75,900 KB
testcase_09 AC 539 ms
94,632 KB
testcase_10 AC 528 ms
94,600 KB
testcase_11 AC 530 ms
94,740 KB
testcase_12 AC 536 ms
94,432 KB
testcase_13 AC 535 ms
94,388 KB
testcase_14 AC 347 ms
103,440 KB
testcase_15 AC 358 ms
103,628 KB
testcase_16 AC 484 ms
97,444 KB
testcase_17 AC 481 ms
99,520 KB
testcase_18 AC 428 ms
99,448 KB
testcase_19 AC 398 ms
102,672 KB
testcase_20 AC 392 ms
102,448 KB
testcase_21 AC 388 ms
83,572 KB
testcase_22 AC 374 ms
83,620 KB
testcase_23 AC 378 ms
83,508 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