結果

問題 No.1293 2種類の道路
ユーザー marroncastlemarroncastle
提出日時 2020-11-20 22:38:19
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 553 ms / 2,000 ms
コード長 1,464 bytes
コンパイル時間 346 ms
コンパイル使用メモリ 87,124 KB
実行使用メモリ 112,304 KB
最終ジャッジ日時 2023-09-30 19:40:50
合計ジャッジ時間 8,189 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 79 ms
71,184 KB
testcase_01 AC 80 ms
70,928 KB
testcase_02 AC 79 ms
70,892 KB
testcase_03 AC 80 ms
71,288 KB
testcase_04 AC 82 ms
70,828 KB
testcase_05 AC 83 ms
71,080 KB
testcase_06 AC 80 ms
71,276 KB
testcase_07 AC 77 ms
71,064 KB
testcase_08 AC 81 ms
71,076 KB
testcase_09 AC 546 ms
90,980 KB
testcase_10 AC 546 ms
89,996 KB
testcase_11 AC 543 ms
90,800 KB
testcase_12 AC 553 ms
91,300 KB
testcase_13 AC 520 ms
89,856 KB
testcase_14 AC 361 ms
112,304 KB
testcase_15 AC 354 ms
111,616 KB
testcase_16 AC 312 ms
91,872 KB
testcase_17 AC 320 ms
95,808 KB
testcase_18 AC 286 ms
96,536 KB
testcase_19 AC 338 ms
94,632 KB
testcase_20 AC 337 ms
94,808 KB
testcase_21 AC 231 ms
78,604 KB
testcase_22 AC 220 ms
78,324 KB
testcase_23 AC 216 ms
77,796 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 i in range(D):
  a,b = map(int, input().split())
  uf1.union(a-1,b-1)
for i in range(W):
  c,d = map(int, input().split())
  uf2.union(c-1,d-1)

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