結果

問題 No.1390 Get together
ユーザー marroncastlemarroncastle
提出日時 2021-02-13 01:52:29
言語 PyPy3
(7.3.15)
結果
RE  
実行時間 -
コード長 1,366 bytes
コンパイル時間 299 ms
コンパイル使用メモリ 87,116 KB
実行使用メモリ 125,964 KB
最終ジャッジ日時 2023-09-27 09:09:14
合計ジャッジ時間 12,123 ms
ジャッジサーバーID
(参考情報)
judge14 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 70 ms
71,348 KB
testcase_01 AC 70 ms
71,308 KB
testcase_02 AC 69 ms
71,288 KB
testcase_03 RE -
testcase_04 RE -
testcase_05 RE -
testcase_06 RE -
testcase_07 RE -
testcase_08 RE -
testcase_09 RE -
testcase_10 RE -
testcase_11 RE -
testcase_12 RE -
testcase_13 RE -
testcase_14 RE -
testcase_15 AC 72 ms
71,612 KB
testcase_16 RE -
testcase_17 AC 395 ms
118,900 KB
testcase_18 RE -
testcase_19 RE -
testcase_20 AC 513 ms
120,320 KB
testcase_21 AC 529 ms
121,232 KB
testcase_22 AC 396 ms
118,364 KB
testcase_23 AC 411 ms
118,544 KB
testcase_24 RE -
testcase_25 AC 513 ms
120,592 KB
testcase_26 RE -
testcase_27 AC 513 ms
120,992 KB
testcase_28 AC 512 ms
120,736 KB
testcase_29 RE -
testcase_30 RE -
testcase_31 AC 503 ms
120,992 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)
uf = UnionFind(N)
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