結果

問題 No.2290 UnUnion Find
ユーザー sepa38
提出日時 2023-05-05 21:29:48
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 1,020 bytes
コンパイル時間 322 ms
コンパイル使用メモリ 81,972 KB
実行使用メモリ 112,128 KB
最終ジャッジ日時 2024-11-23 06:09:05
合計ジャッジ時間 40,049 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 12 WA * 34
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
sys.setrecursionlimit(500000)
class UF:
  def __init__(self, n):
    self.root = [i for i in range(n)]
    self.subt = [1] * n

  def find(self, x):
    if self.root[x] == x:
      return x
    else:
      self.root[x] = self.find(self.root[x])
      return self.root[x]

  def union(self, x, y):
    x, y = self.find(x), self.find(y)
    x, y = min(x, y), max(x, y)
    if x != y:
      self.subt[x] += self.subt[y]
    self.root[y] = x

  def size(self, x):
    return self.subt[self.find(x)]


n, q = map(int, input().split())
uf = UF(n)
s = set([i for i in range(n)])
for _ in range(q):
  query = list(map(lambda x: int(x)-1, input().split()))
  if query[0]:
    v = query[1]
    if uf.size(v) == n:
      print(-1)
      continue
    v = uf.find(v)
    for cnd in s:
      if cnd != v:
        print(cnd + 1)
        break
  else:
    u, v = query[1:]
    u, v = sorted([u, v])
    uf.union(u, v)
    if uf.find(v) != v and v in s:
      s.discard(v)
    if uf.find(u) != u and u in s:
      s.discard(u)
0