import heapq INF = 10**18 def dijkstra(s, edge): n = len(edge) dist = [INF]*n dist[s] = 0 edgelist = [] heapq.heappush(edgelist,(dist[s], s)) while edgelist: minedge = heapq.heappop(edgelist) if dist[minedge[1]] < minedge[0]: continue v = minedge[1] for e in edge[v]: if dist[e[1]] > dist[v]+e[0]: dist[e[1]] = dist[v]+e[0] heapq.heappush(edgelist,(dist[e[1]], e[1])) return dist import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline t = int(input()) n, m = map(int, input().split()) E = [] edge = [set() for i in range(n)] for i in range(m): u, v, w = map(int, input().split()) u, v = u-1, v-1 E.append((u, v, w)) if t == 0: edge[u].add((w, v)) edge[v].add((w, u)) else: edge[u].add((w, v)) ans = INF if t == 0: for u, v, w in E: edge[u].remove((w, v)) edge[v].remove((w, u)) D = dijkstra(v, edge) ans = min(ans, w+D[u]) edge[u].add((w, v)) edge[v].add((w, u)) else: for u, v, w in E: edge[u].remove((w, v)) D = dijkstra(v, edge) ans = min(ans, w+D[u]) edge[u].add((w, v)) if ans < INF: print(ans) else: print(-1)