import sys input = sys.stdin.readline class MinCostFlow: def __init__(self, N): self.N = N self.inf = 10 ** 18 self.G = [[] for i 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 bellman_ford(self, s): dist = [self.inf] * self.N dist[s] = 0 pv = [0] * self.N pe = [0] * self.N while True: update = False for v in range(self.N): if dist[v] == self.inf: continue for i in range(len(self.G[v])): next, cap, cost, _ = self.G[v][i] if cap > 0 and dist[next] > dist[v] + cost: dist[next] = dist[v] + cost update = True pv[next] = v pe[next] = i if not update: break return dist, pv, pe def calc_min_cost_flow(self, s, t, f): result = 0 while f > 0: dist, pv, pe = self.bellman_ford(s) if dist[t] == self.inf: return self.inf flow = f v = t while v != s: flow = min(flow, self.G[pv[v]][pe[v]][1]) v = pv[v] result += flow * dist[t] f -= flow v = t while v != s: d, cap, cost, r = self.G[pv[v]][pe[v]] cap -= flow self.G[pv[v]][pe[v]] = (d, cap, cost, r) rev = self.G[pv[v]][pe[v]][3] d, cap, cost, r = self.G[v][rev] cap += flow self.G[v][rev] = (d, cap, cost, r) v = pv[v] return result N, M = map(int, input().split()) G = MinCostFlow(N) for i in range(M): u, v, c, d = map(int, input().split()) u, v = u - 1, v - 1 G.add_edge(u, v, 1, c) G.add_edge(u, v, 1, d) G.add_edge(v, u, 1, c) G.add_edge(v, u, 1, d) print(G.calc_min_cost_flow(0, N-1, 2))