結果

問題 No.1865 Make Cycle
ユーザー NatsubiSogan
提出日時 2022-03-04 22:25:05
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 1,118 bytes
コンパイル時間 266 ms
コンパイル使用メモリ 82,560 KB
実行使用メモリ 81,216 KB
最終ジャッジ日時 2024-07-18 20:57:08
合計ジャッジ時間 5,395 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 2 WA * 18
権限があれば一括ダウンロードができます

ソースコード

diff #

# 重み付きUnion-Find
class WeightedUnionFind:
	def __init__(self, n: int) -> None:
		self.n = n
		self.par = list(range(n))
		self.rank = [0] * n
		self.weight = [0] * n

	def find(self, x: int) -> int:
		if self.par[x] == x:
			return x
		else:
			y = self.find(self.par[x])
			self.weight[x] += self.weight[self.par[x]]
			self.par[x] = y
			return y

	def unite(self, x: int, y: int, w: int) -> None:
		p, q = self.find(x), self.find(y)
		if self.rank[p] < self.rank[q]:
			self.par[p] = q
			self.weight[p] = w - self.weight[x] + self.weight[y]
		else:
			self.par[q] = p
			self.weight[q] = -w - self.weight[y] + self.weight[x]
			if self.rank[p] == self.rank[q]:
				self.rank[p] += 1

	def same(self, x: int, y: int) -> bool:
		return self.find(x) == self.find(y)

	def diff(self, x: int, y: int) -> int:
		return self.weight[x] - self.weight[y]

n, q = map(int, input().split())
UF = WeightedUnionFind(n)
for i in range(q):
	a, b = map(int, input().split())
	a -= 1; b -= 1
	if UF.same(a, b):
		d = UF.diff(a, b)
		if d < 0: exit(print(i + 1))
		else: UF.unite(a, b, d)
	else:
		UF.unite(a, b, 1)
print(-1)
0