from heapq import heappush, heappop import sys def input(): return sys.stdin.buffer.readline()[:-1] def enc(pos, cost): return cost * 10000 + pos def dec(x): return x % 10000, x // 10000 INF = 10**15 t = int(input()) n, m = map(int, input().split()) adj = [[] for _ in range(n)] for _ in range(m): u, v, w = map(int, input().split()) adj[u-1].append(enc(v-1, w)) if t == 0: adj[v-1].append(enc(u-1, w)) ans = INF for x in range(n): dist = [INF for _ in range(n)] prev = [-1 for _ in range(n)] dist[x] = 0 q = [x] while q: i, c0 = dec(heappop(q)) #print(i, c0) for y in adj[i]: j, c1 = dec(y) if t == 0 and prev[i] == j: continue if dist[j] > c0 + c1: prev[j] = i dist[j] = c0 + c1 heappush(q, enc(j, c0 + c1)) else: #print("! " + str(j) + " " + str(c1)) if t == 0 or j == x: ans = min(ans, c0 + dist[j] + c1) #print("-----") if ans == INF: print(-1) else: print(ans)