import sys import heapq input = sys.stdin.buffer.readline sys.setrecursionlimit(10 ** 7) inf = 10**18 T = int(input()) N, M = map(int, input().split()) edge = [] G = [[] for _ in range(N)] for i in range(M): a, b, c = map(int, input().split()) a -= 1 b -= 1 edge.append((a, b, c)) G[a].append((b, c)) if T == 0: G[b].append((a, c)) def dijkstra(i): s, t, c = edge[i] dist = [inf] * N dist[t] = 0 que = [(0, t)] while que: dv, v = heapq.heappop(que) if dist[v] < dv: continue if v == s: break for u, du in G[v]: if (v, u) in ((s, t), (t, s)): continue if dist[u] > dv + du: dist[u] = dv + du heapq.heappush(que, (dv + du, u)) return c + dist[s] ans = inf for i in range(M): d = dijkstra(i) if d < ans: ans = d if ans >= inf: ans = -1 print(ans)