#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define rep(x, s, t) for(llint (x) = (s); (x) <= (t); (x)++) #define chmin(x, y) (x) = min((x), (y)) #define chmax(x, y) (x) = max((x), (y)) #define all(x) (x).begin(),(x).end() #define inf 1e15 #define mod 998244353 using namespace std; typedef long long llint; typedef long long ll; typedef pair P; struct edge{ int to, cap, cost, rev; edge(){} edge(llint a, llint b, llint c, llint d){ to = a, cap = b, cost = c, rev = d; } }; int n, m, F; int S, T; vector G[500005]; llint dist[500005]; int prevv[500005], preve[500005]; llint h[500005]; void Dijkstra() { for(int i = 0; i <= T; i++) dist[i] = inf; dist[S] = 0, prevv[S] = -1; priority_queue< P, vector

, greater

> Q; Q.push( make_pair(0, S) ); llint v, d; while(Q.size()){ d = Q.top().first; v = Q.top().second; Q.pop(); if(dist[v] < d) continue; for(int i = 0; i < G[v].size(); i++){ if(G[v][i].cap == 0) continue; llint u = G[v][i].to, c = h[v] - h[u] + G[v][i].cost; if(dist[u] > d + c){ dist[u] = d + c; prevv[u] = v; preve[u] = i; Q.push( make_pair(dist[u], u) ); } } } } void add_edge(llint from, llint to, llint cap, llint cost) { G[from].push_back( edge(to, cap, cost, G[to].size()) ); G[to].push_back( edge(from, 0, -cost, G[from].size()-1) ); } int main(void) { ios::sync_with_stdio(0); cin.tie(0); cin >> n >> m; ll u, v, c, d; rep(i, 1, m){ cin >> u >> v >> c >> d ; add_edge(u, v, 1, c); add_edge(v, u, 1, c); add_edge(u, v, 1, d); add_edge(v, u, 1, d); } S = 1, T = n; int f = 2; ll ans = 0; while(f > 0){ Dijkstra(); if(dist[T] >= inf) break; int p = T, flow = f; while(prevv[p] != -1){ flow = min(flow, G[prevv[p]][preve[p]].cap); p = prevv[p]; } p = T; while(prevv[p] != -1){ G[prevv[p]][preve[p]].cap -= flow; G[p][G[prevv[p]][preve[p]].rev].cap += flow; p = prevv[p]; } f -= flow; ans += dist[T] * flow; } if(f > 0) ans = -1; cout << ans << endl; return 0; }