//#define _GLIBCXX_DEBUG #include #define rep(i, n) for(int i=0; i; using vs = vector; using vi = vector; using vvi = vector; template using PQ = priority_queue; template using PQG = priority_queue, greater >; const int INF = 0xccccccc; const ll LINF = 0xcccccccccccccccLL; template inline bool chmax(T1 &a, T2 b) {return a < b && (a = b, true);} template inline bool chmin(T1 &a, T2 b) {return a > b && (a = b, true);} template istream &operator>>(istream &is, pair &p) { return is >> p.first >> p.second;} template ostream &operator<<(ostream &os, const pair &p) { return os << p.first << ' ' << p.second;} template struct MinCostFlow { struct edge { int to, cap; T cost; int rev; }; using P = pair; int V; vector> G; vector h, dist; vector prevv, preve; const T INF; //INF*Fがオーバーフローしない かつ costより十分に大きい MinCostFlow(int n, T INF_):V(n), G(n), h(n), dist(n), prevv(n), preve(n), INF(INF_) {} inline void add(int from, int to, int cap, T cost) { G[from].emplace_back((edge){to, cap, cost, (int)G[to].size()}); G[to].emplace_back((edge){from, 0, -cost, (int)G[from].size()-1}); } //最小費用流//無理な時は-1 T min_cost_flow(const int s, const int t, int f) { T res = 0; while(f > 0) { priority_queue, greater

> que; fill(dist.begin(), dist.end(), INF); dist[s] = 0; que.emplace(0, s); while(!que.empty()) { P p = que.top(); que.pop(); int v = p.second; if(dist[v] < p.first) continue; for(int i = 0; i < (int)G[v].size(); i++) { edge &e = G[v][i]; if(e.cap > 0 and dist[e.to] > dist[v]+e.cost+h[v]-h[e.to]) { dist[e.to] = dist[v]+e.cost+h[v]-h[e.to]; prevv[e.to] = v; preve[e.to] = i; que.emplace(dist[e.to], e.to); } } } if(dist[t] == INF) return -1; for(int v = 0; v < V; v++) h[v] += dist[v]; int d = f; for(int v = t; v != s; v = prevv[v]) d = min(d, G[prevv[v]][preve[v]].cap); f -= d; res += d*h[t]; for(int v = t; v != s; v = prevv[v]) { edge &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } }; //head int main() { ios::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; MinCostFlow mcf(n+2*m, LINF); rep(i, m) { int u, v, c, d; cin >> u >> v >> c >> d; int y = n+i*2, z = y+1; u--; v--; mcf.add(u, y, 2, 0); mcf.add(v, y, 2, 0); mcf.add(z, u, 2, 0); mcf.add(z, v, 2, 0); mcf.add(y, z, 1, c); mcf.add(y, z, 2, d); } cout << mcf.min_cost_flow(0, n-1, 2) << endl; }