結果

問題 No.1293 2種類の道路
ユーザー paruf4paruf4
提出日時 2020-11-21 00:50:52
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 865 ms / 2,000 ms
コード長 1,727 bytes
コンパイル時間 78 ms
コンパイル使用メモリ 10,876 KB
実行使用メモリ 35,856 KB
最終ジャッジ日時 2023-09-30 20:23:11
合計ジャッジ時間 12,136 ms
ジャッジサーバーID
(参考情報)
judge11 / judge13
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 17 ms
8,116 KB
testcase_01 AC 19 ms
8,072 KB
testcase_02 AC 18 ms
7,980 KB
testcase_03 AC 17 ms
8,076 KB
testcase_04 AC 17 ms
8,076 KB
testcase_05 AC 17 ms
8,080 KB
testcase_06 AC 17 ms
8,176 KB
testcase_07 AC 17 ms
8,072 KB
testcase_08 AC 17 ms
8,120 KB
testcase_09 AC 862 ms
18,084 KB
testcase_10 AC 847 ms
18,264 KB
testcase_11 AC 849 ms
18,300 KB
testcase_12 AC 865 ms
18,144 KB
testcase_13 AC 851 ms
18,280 KB
testcase_14 AC 586 ms
35,848 KB
testcase_15 AC 588 ms
35,856 KB
testcase_16 AC 781 ms
22,004 KB
testcase_17 AC 803 ms
25,748 KB
testcase_18 AC 500 ms
26,736 KB
testcase_19 AC 512 ms
20,272 KB
testcase_20 AC 500 ms
20,412 KB
testcase_21 AC 652 ms
8,160 KB
testcase_22 AC 642 ms
8,068 KB
testcase_23 AC 642 ms
8,052 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, d, w = map(int, input().split())
uf1 = UnionFind(n)
uf2 = UnionFind(n)
for _ in range(d):
    p, q = map(int, input().split())
    p -= 1
    q -= 1
    uf1.union(p, q)

for _ in range(w):
    p, q = map(int, input().split())
    p -= 1
    q -= 1
    uf2.union(p, q)

res = 0

# print(uf1.groups())
# print(uf2.groups())
for g in uf2.groups():
    goal = uf2.size(g[0])
    start = 0
    used = {}
    for v in g:
        r = uf1.find(v)
        if r not in used:
            start += uf1.size(r)
            used[r] = 1
    res += (start-1)*goal

print(res)
0