inf = (1 << 63)-1 from heapq import * t=int(input()) n,m=map(int,input().split()) to=[[] for _ in range(n)] uvw=[] for i in range(m): u,v,w=map(int,input().split()) u,v=u-1,v-1 to[u].append((v,w,i)) if t==0: to[v].append((u,w,i)) uvw.append((u,v,w)) def solve(s,g,lim): dd=[inf]*n hp=[] heappush(hp,(0,s)) dd[s]=0 while hp: d,u=heappop(hp) if u==g:return d if d>dd[u]:continue for v,w,i in to[u]: if fin[i]:continue if dd[v]<=d+w or d+w>=lim:continue dd[v]=d+w heappush(hp,(d+w,v)) return inf fin=[False]*m ans=inf for i,(u,v,w) in enumerate(uvw): if fin[i]:continue fin[i]=True ret=solve(v,u,ans-w)+w if ret