#include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; const int MAX_V = 200010; const int INF = INT_MAX; typedef pair P; int V; struct Point { int y; int x; Point(int y = -1, int x = -1) { this->y = y; this->x = x; } }; struct Edge { int to; ll cap; ll cost; int rev; Edge(int to = -1, ll cap = -1, ll cost = -1, int rev = -1) { this->to = to; this->cap = cap; this->cost = cost; this->rev = rev; } }; ll h[MAX_V]; int dist[MAX_V]; int prevv[MAX_V]; int preve[MAX_V]; vector G[MAX_V]; class MinCostFlow { public: int V; MinCostFlow(int V) { this->V = V; } void add_edge(int from, int to, ll cap, ll cost) { G[from].push_back(Edge(to, cap, cost, G[to].size())); G[to].push_back(Edge(from, 0, -cost, G[from].size() - 1)); } ll min_cost_flow(int s, int t, ll flow_limit) { ll f = 0; ll totalCost = 0; fill(h, h + MAX_V, 0); while (f < flow_limit) { // fprintf(stderr, "f: %lld, limit: %lld\n", f, flow_limit); priority_queue, greater

> pque; fill(dist, dist + V, INF); dist[s] = 0; pque.push(P(0, s)); while (!pque.empty()) { P p = pque.top(); pque.pop(); int v = p.second; if (dist[v] < p.first) continue; for (int i = 0; i < (int) G[v].size(); ++i) { Edge *edge = &G[v][i]; if (edge->cap <= 0) continue; ll cost = edge->cost + h[v] - h[edge->to]; if (dist[edge->to] - dist[v] > cost) { dist[edge->to] = dist[v] + cost; prevv[edge->to] = v; preve[edge->to] = i; pque.push(P(dist[edge->to], edge->to)); } } } if (dist[t] == INF) { return -1; } for (int v = 0; v < V; ++v) { h[v] += dist[v]; } ll c = flow_limit - f; for (int v = t; v != s; v = prevv[v]) { c = min(c, G[prevv[v]][preve[v]].cap); } f += c; totalCost += c * h[t]; // fprintf(stderr, "h[s]: %d, h[t]: %d, cost: %d, prev_cost: %d\n", h[s], h[t], cost, prev_cost); for (int v = t; v != s; v = prevv[v]) { Edge *edge = &G[prevv[v]][preve[v]]; edge->cap -= c; G[v][edge->rev].cap += c; } } return totalCost; } }; int main() { int N, M; cin >> N >> M; V = N + 3; MinCostFlow mcf(V); int u, v; ll c, d; for (int i = 0; i < M; ++i) { cin >> u >> v >> c >> d; mcf.add_edge(u, v, 1, c); mcf.add_edge(v, u, 1, c); mcf.add_edge(u, v, 1, d); mcf.add_edge(v, u, 1, d); } int s = N + 1; int t = N + 2; mcf.add_edge(s, 1, 2, 0); mcf.add_edge(N, t, 2, 0); ll res = mcf.min_cost_flow(s, t, 2); cout << res << endl; return 0; }