'''
题目的意思是在无向图中求1到N的所有可能路径中第K+1大的边的最小值是多少
可以进行二分,假设有一个答案X, 那图中必然存在至少一条路径上,比X长的边
数量小于等于X,二分时候每次验证这个约束是否成立即可
验证方法: 将长度大于X的边权重改为1,权重小于等于X的边权重改为0,然后求最短路,
最短路的数值就是所有路径中经过长度大于X的边的最少数量,如果这个数量小于等于K,
则X是一个合法值,二分搜索搜出来所有合法X的最小值即可
'''
'''
SPFA算法,解带负权边的有向图和不带负权边的无向图的单源
最短路问题
'''
from collections import deque
class SPFA:
# start_node 为起始点,edges是边的三元组(节点1, 节点2, 边权重) is_directed表示是否是有向图
# 包含节点为1, 2, 3, 4, ..... max_node_num
def __init__(self, start_node, edges, is_directed, max_node_num):
self.edges = edges[::]
self.start_node = start_node
self.is_directed = is_directed
self.max_node_num = max_node_num
# 获取最短路径长度的列表[(节点1,长度1), (节点2, 长度2) .....]
def getMinPathLen(self):
return self.getMinInfo()
def getMinInfo(self):
link = {}
dis = [0x7fffffff] * (self.max_node_num+1)
dis[self.start_node] = 0
for a, b, w in self.edges:
if not self.is_directed:
# 无向图检查是否有负边
if w < 0:
return None
if a not in link:
link[a] = []
if b not in link:
link[b] = []
link[a].append((b, w))
link[b].append((a, w))
else:
if a not in link:
link[a] = []
link[a].append((b, w))
updated_nodes = deque()
updated_nodes.append(self.start_node)
in_que = [0] * (self.max_node_num + 1)
in_que[self.start_node] = 1
# 进行V次迭代,第V次检查是否是无解情况
iter_times = 0
while iter_times < self.max_node_num:
update_flag = False
# 利用上一轮迭代距离变小的点进行松弛操作
node_num = len(updated_nodes)
for _ in range(node_num):
a = updated_nodes.popleft()
in_que[a] = 0
if a not in link:
continue
for b, w in link[a]:
new_dis = 0x7fffffff if dis[a] == 0x7fffffff else dis[a] + w
if new_dis < dis[b]:
dis[b] = new_dis
update_flag = True
if in_que[b] == 0:
in_que[b] = 1
updated_nodes.append(b)
iter_times += 1
if iter_times == self.max_node_num:
if update_flag:
return None
if not update_flag:
break
#return [[node, dis[node]] for node in range(1, self.max_node_num+1)]
return dis
N, M, K = map(int, input().split())
all_w = set()
edges = []
for i in range(M):
a, b, w = map(int, input().split())
edges.append((a, b, w))
all_w.add(w)
w_arr = list(all_w)
w_arr.sort()
w_arr = [0] + w_arr
def is_valid(X):
e = [(a, b, 0) if w <= X else (a, b, 1) for a, b, w in edges]
algo = SPFA(1, e, is_directed=False, max_node_num=N)
dis = algo.getMinPathLen()
return dis[N] <= K
l, r = 0, len(w_arr)-1
ans = -1
while l <= r:
mid = l + (r-l) // 2
if is_valid(w_arr[mid]):
r = mid - 1
ans = w_arr[mid]
else:
l = mid + 1
print(ans)