structEdge { int to, next, w; } e[1000000]; int c1, head[maxn], in[maxn], out[maxn]; inlinevoidadd_edge(int u, int v, int w){ e[c1].to = v; e[c1].w = w; e[c1].next = head[u]; head[u] = c1++; }
inlinevoidAdd_edge(int u, int v, int l, int r){ add_edge(u, v, r - l); add_edge(v, u, 0); in[v] += l; out[u] += l; }
int s, t, ss, tt, dep[maxn]; boolbfs(){ fill(dep, dep + maxn, 0); dep[s] = 1; queue<int> Q; Q.push(s); while (!Q.empty()) { int u = Q.front(); Q.pop(); for (int i = head[u]; ~i; i = e[i].next) { int v = e[i].to, w = e[i].w; if (w > 0 && !dep[v]) { dep[v] = dep[u] + 1; if (v == t) return1; Q.push(v); } } } return0; }
intdfs(int u, int _w){ if (u == t || !_w) return _w; int s = 0; for (int i = head[u]; ~i; i = e[i].next) { int v = e[i].to, w = e[i].w; if (dep[v] == dep[u] + 1 && w > 0) { int di = dfs(v, min(_w - s, w)); e[i].w -= di; e[i ^ 1].w += di; s += di; if (s == _w) break; } } if (s < _w) dep[u] = 0; return s; }
intdinic(){ int mf = 0; while (bfs()) mf += dfs(s, INF); return mf; }
cin >> n >> m; s = 0; t = n + 1; for (int i = 1; i <= m; ++i) { int x, y, l, r; cin >> x >> y >> l >> r; Add_edge(x, y, l, r); } int mf = 0; for (int i = 1; i <= n; ++i) { if (in[i] > out[i]) Add_edge(s, i, 0, in[i] - out[i]); else Add_edge(i, t, 0, out[i] - in[i]); mf += max(0, in[i] - out[i]); } cout << (dinic() == mf); return0; }
cin >> n >> m; s = 0; t = n + 1; ss = n + 2; tt = n + 3; for (int i = 1; i <= m; ++i) { int x, y, l, r; cin >> x >> y >> l >> r; Add_edge(x, y, l, r); } Add_edge(t, s, 0, INF); int mf = 0; for (int i = s; i <= t; ++i) { if (in[i] > out[i]) Add_edge(ss, i, 0, in[i] - out[i]); else Add_edge(i, tt, 0, out[i] - in[i]); mf += max(0, in[i] - out[i]); } swap(s, ss); swap(t, tt); if (dinic() != mf) returncout << "-1\n", 0; swap(s, ss); swap(t, tt); int ans = 0; for (int i = head[s]; ~i; i = e[i].next) if (e[i].to == t) ans = e[i].w, e[i].w = e[i ^ 1].w = 0; for (int i = head[ss]; ~i; i = e[i].next) e[i].w = e[i ^ 1].w = 0; for (int i = head[tt]; ~i; i = e[i].next) e[i].w = e[i ^ 1].w = 0; cout << ans + dinic() << "\n"; return0; }