結果

問題 No.1865 Make Cycle
ユーザー NatsubiSoganNatsubiSogan
提出日時 2022-03-04 22:25:05
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 1,118 bytes
コンパイル時間 343 ms
コンパイル使用メモリ 86,888 KB
実行使用メモリ 83,504 KB
最終ジャッジ日時 2023-09-26 01:32:39
合計ジャッジ時間 6,560 ms
ジャッジサーバーID
(参考情報)
judge12 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 WA -
testcase_01 WA -
testcase_02 WA -
testcase_03 AC 105 ms
79,192 KB
testcase_04 AC 176 ms
80,680 KB
testcase_05 WA -
testcase_06 WA -
testcase_07 WA -
testcase_08 WA -
testcase_09 WA -
testcase_10 WA -
testcase_11 WA -
testcase_12 WA -
testcase_13 WA -
testcase_14 WA -
testcase_15 WA -
testcase_16 WA -
testcase_17 WA -
testcase_18 WA -
testcase_19 WA -
testcase_20 AC 70 ms
71,388 KB
testcase_21 AC 68 ms
71,604 KB
testcase_22 AC 69 ms
71,452 KB
testcase_23 AC 67 ms
71,440 KB
権限があれば一括ダウンロードができます

ソースコード

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