#O(ElogV),頂点数10**5以上の場合は避ける import heapq def dijkstra_heap(s,edge): N = len(edge) dists = [float('inf')] * N #始点sから各頂点への最短距離 prev = [-1]*N used = [False] * N dists[s] = 0 used[s] = True vlist = [] #vlist : [sからの暫定(未確定)最短距離,頂点]のリスト #edge[s] : sから出る枝の[重み,終点]のリスト for v,d in edge[s]: heapq.heappush(vlist,(d,s,v)) #sの隣の点は枝の重さがそのまま暫定最短距離となる while len(vlist): #まだ使われてない頂点の中から最小の距離のものを探す→確定させる d,u,v = heapq.heappop(vlist) #[d,v]:[sからの(確定)最短距離,頂点] if used[v]: continue dists[v] = d prev[v] = u used[v] = True for w,d in edge[v]: if not used[w]: heapq.heappush(vlist,(dists[v]+d,v,w)) return dists, prev import sys,os,io input = sys.stdin.readline #input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline N, M = map(int, input().split()) edge = [[] for _ in range(N)] edges = {} after = {} for i in range(M): u,v,c,d = map(int, input().split()) u -= 1 v -= 1 edge[u].append((v,c)) edge[v].append((u,c)) edges[(u,v)] = c edges[(v,u)] = c after[(u,v)] = d after[(v,u)] = d dists1, prev1 = dijkstra_heap(0, edge) ans = dists1[-1] v = N-1 while v!=0: w = prev1[v] edges[(w,v)] = after[(w,v)] edges[(v,w)] = after[(v,w)] v = w new_edge = [[] for _ in range(N)] for i in range(N): for v,c in edge[i]: new_edge[i].append((v,edges[(i,v)])) dists2, prev2 = dijkstra_heap(0,new_edge) ans += dists2[-1] print(ans)