T = int(input()) N,M = map(int,input().split()) G = [[] for _ in range(N+1)] edge = [] for _ in range(M): u,v,w = map(int,input().split()) G[u].append((v,w)) if T == 0: G[v].append((u,w)) edge.append((u,v,w)) import heapq q = [] heapq.heapify(q) INF = 10 ** 15 _min = INF def check(e): global _min dist = [INF] * (N + 1) start,end,w = e dist[end] = 0 heapq.heappush(q,(0,end)) while q: d,now = heapq.heappop(q) #if now == start:break if d > dist[now]:continue for v,ww in G[now]: if dist[v] > d + ww: if now != end or v != start: dist[v] = d + ww heapq.heappush(q,(d+ww,v)) if dist[start] + w < _min: _min = dist[start] + w for e in edge: check(e) if _min == INF: print(-1) else: print(_min)