結果

問題 No.1293 2種類の道路
ユーザー tktk_snsntktk_snsn
提出日時 2022-06-10 00:46:07
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 248 ms / 2,000 ms
コード長 1,364 bytes
コンパイル時間 148 ms
コンパイル使用メモリ 81,800 KB
実行使用メモリ 102,304 KB
最終ジャッジ日時 2023-10-21 04:34:23
合計ジャッジ時間 5,799 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 35 ms
55,392 KB
testcase_01 AC 35 ms
55,392 KB
testcase_02 AC 35 ms
55,392 KB
testcase_03 AC 37 ms
55,392 KB
testcase_04 AC 38 ms
55,392 KB
testcase_05 AC 37 ms
55,392 KB
testcase_06 AC 35 ms
55,392 KB
testcase_07 AC 34 ms
55,392 KB
testcase_08 AC 37 ms
55,392 KB
testcase_09 AC 245 ms
83,656 KB
testcase_10 AC 228 ms
83,556 KB
testcase_11 AC 248 ms
83,684 KB
testcase_12 AC 241 ms
83,680 KB
testcase_13 AC 226 ms
83,676 KB
testcase_14 AC 176 ms
92,932 KB
testcase_15 AC 169 ms
93,112 KB
testcase_16 AC 189 ms
87,412 KB
testcase_17 AC 178 ms
88,520 KB
testcase_18 AC 155 ms
91,020 KB
testcase_19 AC 181 ms
102,304 KB
testcase_20 AC 174 ms
102,304 KB
testcase_21 AC 146 ms
75,976 KB
testcase_22 AC 158 ms
76,080 KB
testcase_23 AC 142 ms
75,944 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)


class UF_tree:
    def __init__(self, n):
        self.root = [-1] * (n + 1)

    def find(self, x):
        stack = []
        while self.root[x] >= 0:
            stack.append(x)
            x = self.root[x]
        for i in stack:
            self.root[i] = x
        return x

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

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return False
        if -self.root[x] > -self.root[y]:
            x, y = y, x
        self.root[y] += self.root[x]
        self.root[x] = y
        return True

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


N, D, W = map(int, input().split())
car = UF_tree(N)
walk = UF_tree(N)

for _ in range(D):
    a, b = map(int, input().split())
    car.unite(a-1, b-1)

for _ in range(W):
    a, b = map(int, input().split())
    walk.unite(a-1, b-1)

ans = 0
group = defaultdict(list)
for i in range(N):
    group[car.find(i)].append(i)

ans = 0
for k in group.keys():
    used = set()
    sz = 0
    for i in group[k]:
        x = walk.find(i)
        if x in used:
            continue
        sz += walk.size(x)
        used.add(x)
    ans += len(group[k]) * sz
print(ans - N)
0