#!/usr/bin/env python3 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 = [g[0] for g in G] idx = [bisect.bisect_left(frm, v) for v in range(N + 2)] def dijkstra(a, b): dist = [INF] * (N + 1) dist[a] = 0 q = [(0,a)] while q: dv, v = heappop(q) if dv > dist[v]: continue if v == b: return dv for e in range(idx[v], idx[v + 1]): _, w, c = G[e] if (v, w) == (a, b): continue dw = dv + c if dist[w] > dw: dist[w] = dw heappush(q, (dw,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 に、直接ではない行く ans = min(ans, x + c) if ans == INF: ans = -1 return ans print(main())