import sys input = sys.stdin.readline from heapq import heappush, heappop inf = 10**18 def dijkstra(s, g, G, t): # ゴールがない場合はg=-1とする。 N = len(G) def cost(v, m): return v * N + m dist = [inf] * N mindist = [inf] * N seen = [False] * N Edge = [set() for i in range(N)] Q = [(cost(0, s), -1)] while Q: c, p = heappop(Q) c, m = divmod(c, N) if seen[m]: continue seen[m] = True dist[m] = c if t == 0: Edge[p].add(m) Edge[m].add(p) else: Edge[p].add(m) #------heapをアップデートする。-------- for u, C in G[m]: if seen[u]: continue newdist = dist[m] + C #------------------------------------ if newdist >= mindist[u]: continue mindist[u] = newdist heappush(Q, (cost(newdist, u), m)) return dist, Edge T = int(input()) N, M = map(int, input().split()) G = [[] for i in range(N)] E = [] if T == 0: for i in range(M): u, v, c = map(int, input().split()) u, v = u - 1, v - 1 G[u].append((v, c)) G[v].append((u, c)) E.append((u, v, c)) ans = inf for s in range(N): D, Edge = dijkstra(s, -1, G, T) for u, v, c in E: if v in Edge[u]: continue ans = min(ans, D[u] + D[v] + c) else: for i in range(M): u, v, c = map(int, input().split()) u, v = u - 1, v - 1 G[u].append((v, c)) E.append((u, v, c)) ans = inf for s in range(N): D, Edge = dijkstra(s, -1, G, T) for u, v, c in E: if v != s: continue ans = min(ans, D[u] + c) print(ans) if ans != inf else print(-1)