from collections import defaultdict from heapq import heappush, heappop INF = 1 << 60 T = int(input()) N, M = map(int, input().split()) adj = defaultdict(list) for _ in range(M): U, V, W = map(int, input().split()) U -= 1 V -= 1 adj[U].append((V, W)) if T == 0: adj[V].append((U, W)) def solve(): res = INF for s in range(N): for t, tw in adj[s]: # 辺 (s, t) を除外し、t から s への最短距離を求める dists = [INF] * N dists[t] = 0 q = [(0, t)] while q: d, v = heappop(q) if dists[v] != d: continue for to, w in adj[v]: if (v, to) == (t, s): continue nd = dists[v] + w if dists[to] > nd: dists[to] = nd heappush(q, (nd, to)) res = min(res, dists[s] + tw) if res == INF: return -1 return res ans = solve() print(ans)