import sys import bisect from heapq import * read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines INF = 1 << 60 T = int(readline()) N, M = map(int, readline().split()) G = [] for e in range(M): u, v, c = map(int, readline().split()) G.append((u, v, c)) if T == 0: G.append((v, u, c)) G.sort() frm, to, cost = zip(*G) idx = [bisect.bisect_left(frm, v) for v in range(N + 2)] def dijkstra(S, T): dist = [INF] * (N + 1) dist[S] = 0 q = [0 << 15 | S] while q: dv, v = divmod(heappop(q), 1 << 15) if dv > dist[v]: continue if v == T: return dv for e in range(idx[v], idx[v + 1]): _, w, c = G[e] if (v, w) == (S, T) or (w, v) == (T, S): continue dw = dv + c if dist[w] > dw: dist[w] = dw heappush(q, dw << 15 | w) return INF def main(): done = set() ans = INF for u, v, c in G: if (u, v) in done: continue done.add((u, v)) done.add((v, u)) x = dijkstra(v, u) # v から u に、直接ではない行く x = x + c # cycle length ans = min(ans, x) if ans == INF: ans = -1 return ans print(main())