結果

問題 No.1293 2種類の道路
ユーザー 👑 tatyam
提出日時 2020-05-24 03:05:06
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 506 ms / 2,000 ms
コード長 1,374 bytes
コンパイル時間 326 ms
コンパイル使用メモリ 82,228 KB
実行使用メモリ 107,804 KB
最終ジャッジ日時 2024-07-04 18:32:23
合計ジャッジ時間 7,157 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 22
権限があれば一括ダウンロードができます

ソースコード

diff #

class UnionFind:
    def __init__(self, size):
        self.data = [-1] * size
    def root(self, x):
        if self.data[x] < 0:
            return x
        ans = self.root(self.data[x])
        self.data[x] = ans
        return ans
    def unite(self, x, y):
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return False
        if self.data[x] > self.data[y]:
            x, y = y, x
        self.data[x] += self.data[y]
        self.data[y] = x
        return True
    def size(self, x):
        return -self.data[self.root(x)]

n, d, w = map(int, input().split())
assert(2 <= n <= 100000)
assert(1 <= d <= min(100000, n * (n + 1) // 2))
assert(1 <= w <= min(100000, n * (n + 1) // 2))

a = []
for i in range(d):
    x, y = map(int, input().split())
    assert(1 <= x < y <= n)
    a.append((x - 1, y - 1))
assert(len(set(a)) == d)
b = []
for i in range(w):
    x, y = map(int, input().split())
    assert(1 <= x < y <= n)
    b.append((x - 1, y - 1))
assert(len(set(b)) == w)

car = UnionFind(n)
walk = UnionFind(n)
for x, y in a:
    car.unite(x, y)
for x, y in b:
    walk.unite(x, y)

cnt = [0] * n
s = [set() for i in range(n)]
for i in range(n):
    x = car.root(i)
    y = walk.root(i)
    if y not in s[x]:
        s[x].add(y)
        cnt[x] += walk.size(y)

ans = 0
for i in range(n):
    ans += cnt[car.root(i)] - 1
print(ans)
0