AcWing 257. 关押罪犯
原题链接
中等
作者:
皓首不倦
,
2020-08-22 15:02:19
,
所有人可见
,
阅读 433
'''
二分枚举可能的边长上界,所有大于上界的边构成图,判断该图是不是二分图即可
二分方式可以找出最小的上界
'''
import sys
n, m = map(int, input().split())
edges = []
for i in range(m):
s = sys.stdin.readline()
a, b, w = map(int, s.split())
edges.append((a, b, w))
# 判断是否是二分图
def is_valid(e):
link = {}
color = {}
for a, b in e:
if a not in link:
link[a] = []
if b not in link:
link[b] = []
link[a].append(b)
link[b].append(a)
color[a] = None
color[b] = None
def __dfs(cur, c) -> bool:
color[cur] = c
for ne in link[cur]:
if color[ne] == c:
return False
elif color[ne] is None:
if not __dfs(ne, 1-c):
return False
return True
for node in link.keys():
if color[node] is None:
if not __dfs(node, 0):
return False
return True
l, r = 0, 100000
ans = -1
while l <= r:
mid = l + (r-l) // 2
e = []
for a, b, w in edges:
if w > mid:
e.append((a, b))
if is_valid(e):
ans = mid
r = mid - 1
else:
l = mid + 1
print(ans)