#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; using ull = unsigned long long; template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } //template T gcd(T a, T b) { a = abs(a), b = abs(b); while (b > 0) { tie(a, b) = make_pair(b, a % b); }return a; } //mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count()); constexpr long long INF = 1LL << 60; constexpr int inf = 1000000007; //constexpr long long mod = 1000000007LL; constexpr long long mod = 998244353; struct PrimalDual { struct edge { int to; ll cap; ll cost; int rev; bool isrev; edge(int _to, ll _cap, ll _cost, int _rev, bool _isrev) :to(_to), cap(_cap), cost(_cost), rev(_rev), isrev(_isrev) {} }; vector> graph; vector potential, min_cost; vector prevv, preve; PrimalDual(int V) :graph(V) {} void add_edge(int from, int to, ll cap, ll cost) { graph[from].emplace_back(to, cap, cost, graph[to].size(), false); graph[to].emplace_back(from, 0, -cost, graph[from].size() - 1, true); } ll min_cost_flow(int s, int t, ll f) { int V = graph.size(); ll res = 0; priority_queue, vector>, greater<>> pq; potential.assign(V, 0); preve.assign(V, -1); prevv.assign(V, -1); while (f > 0) { min_cost.assign(V, INF); pq.emplace(0, s); min_cost[s] = 0; while (!pq.empty()) { auto cur = pq.top(); pq.pop(); if (min_cost[cur.second] < cur.first) continue; for (int i = 0; i < graph[cur.second].size(); i++) { edge& e = graph[cur.second][i]; ll nextCost = min_cost[cur.second] + e.cost + potential[cur.second] - potential[e.to]; if (e.cap > 0 and min_cost[e.to] > nextCost) { min_cost[e.to] = nextCost; prevv[e.to] = cur.second; preve[e.to] = i; pq.emplace(min_cost[e.to], e.to); } } } if (min_cost[t] == INF) return -1; for (int v = 0; v < V; v++) potential[v] += min_cost[v]; ll add_flow = f; for (int v = t; v != s; v = prevv[v]) { chmin(add_flow, graph[prevv[v]][preve[v]].cap); } f -= add_flow; res += add_flow * potential[t]; for (int v = t; v != s; v = prevv[v]) { edge& e = graph[prevv[v]][preve[v]]; e.cap -= add_flow; graph[v][e.rev].cap += add_flow; } } return res; } }; int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int n, m; cin >> n >> m; PrimalDual g(n); for (int i = 0; i < m; i++) { int u, v, c, d; cin >> u >> v >> c >> d; u--; v--; 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); } cout << g.min_cost_flow(0, n - 1, 2) << endl; }