import sys input = sys.stdin.readline class Mincostflow: def __init__(self, N): self.N = N self.G = [[] for _ in range(N)] def add_edge(self, u, v, cap, cost): self.G[u].append([v, cap, cost, len(self.G[v])]) self.G[v].append([u, 0, -cost, len(self.G[u])-1]) def min_cost_flow(self, s, t, f): res = 0 while f>0: dist = [10**18]*self.N dist[s] = 0 prev_v = [-1]*self.N prev_e = [-1]*self.N update = True while update: update = False for v in range(self.N): if dist[v]==10**18: continue for i in range(len(self.G[v])): nv, cap, cost, _ = self.G[v][i] if cap>0 and dist[nv]>dist[v]+cost: dist[nv] = dist[v]+cost prev_v[nv] = v prev_e[nv] = i update = True if dist[t]==10**18: return -1 d = f v = t while v!=s: d = min(d, self.G[prev_v[v]][prev_e[v]][1]) v = prev_v[v] f -= d res += d*dist[t] v = t while v!=s: self.G[prev_v[v]][prev_e[v]][1] -= d rev = self.G[prev_v[v]][prev_e[v]][3] self.G[v][rev][1] += d v = prev_v[v] return res N, M = map(int, input().split()) mcf = Mincostflow(N) for _ in range(M): u, v, c, d = map(int, input().split()) mcf.add_edge(u-1, v-1, 1, c) mcf.add_edge(v-1, u-1, 1, c) mcf.add_edge(u-1, v-1, 1, d) mcf.add_edge(v-1, u-1, 1, d) print(mcf.min_cost_flow(0, N-1, 2))