結果

問題 No.1390 Get together
ユーザー marroncastlemarroncastle
提出日時 2021-02-13 01:55:33
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 537 ms / 2,000 ms
コード長 1,368 bytes
コンパイル時間 1,020 ms
コンパイル使用メモリ 86,824 KB
実行使用メモリ 121,276 KB
最終ジャッジ日時 2023-09-27 09:12:08
合計ジャッジ時間 11,038 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 70 ms
71,320 KB
testcase_01 AC 69 ms
71,588 KB
testcase_02 AC 70 ms
71,420 KB
testcase_03 AC 121 ms
78,676 KB
testcase_04 AC 118 ms
78,468 KB
testcase_05 AC 120 ms
78,880 KB
testcase_06 AC 115 ms
78,712 KB
testcase_07 AC 114 ms
78,780 KB
testcase_08 AC 114 ms
78,676 KB
testcase_09 AC 118 ms
78,668 KB
testcase_10 AC 69 ms
71,304 KB
testcase_11 AC 70 ms
71,260 KB
testcase_12 AC 71 ms
71,516 KB
testcase_13 AC 70 ms
71,572 KB
testcase_14 AC 70 ms
71,380 KB
testcase_15 AC 70 ms
71,284 KB
testcase_16 AC 262 ms
100,500 KB
testcase_17 AC 378 ms
118,776 KB
testcase_18 AC 271 ms
110,320 KB
testcase_19 AC 517 ms
120,772 KB
testcase_20 AC 506 ms
120,416 KB
testcase_21 AC 528 ms
121,104 KB
testcase_22 AC 398 ms
118,828 KB
testcase_23 AC 414 ms
118,656 KB
testcase_24 AC 408 ms
116,972 KB
testcase_25 AC 506 ms
120,900 KB
testcase_26 AC 474 ms
120,136 KB
testcase_27 AC 508 ms
120,928 KB
testcase_28 AC 537 ms
121,276 KB
testcase_29 AC 502 ms
120,924 KB
testcase_30 AC 493 ms
119,904 KB
testcase_31 AC 499 ms
120,820 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, M = map(int, input().split())
setlis = [set() for _ in range(N)]
for i in range(N):
  b,c = map(int, input().split())
  setlis[c-1].add(b-1)
uf = UnionFind(M)
ans = 0
for i in range(N):
  lis = list(setlis[i])
  if not len(lis): continue
  a = lis[0]
  for l in lis[1:]:
    if not uf.same(a,l):
      ans += 1
      uf.union(a,l)
print(ans)
0