結果
| 問題 |
No.1865 Make Cycle
|
| コンテスト | |
| ユーザー |
shobonvip
|
| 提出日時 | 2022-03-04 23:20:01 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
WA
|
| 実行時間 | - |
| コード長 | 2,714 bytes |
| コンパイル時間 | 278 ms |
| コンパイル使用メモリ | 82,048 KB |
| 実行使用メモリ | 117,248 KB |
| 最終ジャッジ日時 | 2024-07-18 21:54:47 |
| 合計ジャッジ時間 | 9,373 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 WA * 3 |
| other | WA * 20 |
ソースコード
import sys
sys.setrecursionlimit(200000)
class UnionFind:
"""
class UnionFind
https://note.nkmk.me/python-union-find/
order O(log(n))
n = the number of elements
parents = the list that contains "parents" of x. be careful that it doesn't contain "root" of x.
"""
def __init__(self, n):
"""
make UnionFind
:param n: the number of elements
"""
self.n = n
self.parents = [-1]*n
self.rr = [0] * n
def find(self, x):
"""
:param x: an element
:return: the root containing 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, r):
"""
:param x, y: an element
"""
# root
x = self.find(x)
y = self.find(y)
if x == y:
# already same group so do nothing
return
if self.parents[x] > self.parents[y]:
# the root should be min of group
x, y = y, x
# remind that x, y is the root, x < y, then, y unions to x.
self.parents[x] += self.parents[y]
self.rr[x] = max([self.rr[x], self.rr[y], r])
# and then y's parent is x.
self.parents[y] = x
def size(self, x):
# return the size of group
return -self.parents[self.find(x)]
def same(self, x, y):
# return whether the x, y are in same group
return self.find(x) == self.find(y)
def members(self, x):
# return members of group
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
# return all roots
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
# return how many groups
return len(self.roots())
def all_group_members(self):
# return all members of all groups
return {r:self.members(r) for r in self.roots()}
n, m = map(int, input().split())
ikeru = [[] for i in range(n)]
ikeruinv = [[] for i in range(n)]
for i in range(m):
a, b = map(int, input().split())
ikeru[a-1].append((b-1, i))
ikeruinv[b-1].append((a-1, i))
tansaku = [0 for i in range(n)]
tansakuinv = [0 for i in range(n)]
dat = [0 for i in range(n)]
ichi = 0
def dfs(a):
global ichi
if tansaku[a] == 1:
return
tansaku[a] = 1
for i, v in ikeru[a]:
if tansaku[i] == 0:
dfs(i)
dat[a] = ichi
ichi += 1
return
def dfsinv(a):
global ichi
if tansakuinv[a] == 1:
return
tansakuinv[a] = 1
for i, v in ikeruinv[a]:
if tansakuinv[i] == 0:
union.union(i, a, v)
dfsinv(i)
return
for i in range(n):
dfs(i)
# print(dat)
union = UnionFind(n)
u = [(i, dat[i]) for i in range(n)]
u.sort(key=lambda x:-x[1])
for i, d in u:
dfsinv(i)
# print(union.all_group_members())
ans = 10**18
for i in range(n):
if union.parents[i] < 0:
ans = min(ans, union.rr[i])
if ans == 10**18:
print(-1)
else:
print(ans)
shobonvip