对于每一个u,v,a,b,c
建(S,u,a) (u,v,a+c-2*b) (v,T,c) (S,v,a) (v,u,a+c-2*b) (u,T,c)
最后答案为(2*sum(a+c)-最大流)/2
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int MAXN = 505; const int MAXM = 100000; int Head[MAXN], cur[MAXN], lev[MAXN], to[MAXM << 1], nxt[MAXM << 1], f[MAXM << 1], ed = 1, S, T; inline void addedge(int u, int v, int cap) { to[++ed] = v; nxt[ed] = Head[u]; Head[u] = ed; f[ed] = cap; to[++ed] = u; nxt[ed] = Head[v]; Head[v] = ed; f[ed] = 0; return; } inline bool BFS(int x) { int u; for (int i = 0; i <= x; i++) lev[i] = -1; queue<int>q; lev[S] = 0; q.push(S); while (q.size()) { u = q.front(); q.pop(); for (int i = Head[u]; i; i = nxt[i]) if (f[i] && lev[to[i]] == -1) { lev[to[i]] = lev[u] + 1; q.push(to[i]); } } for (int i = 0; i <= x; i++) cur[i] = Head[i]; return lev[T] != -1; } inline int DFS(int u, int maxf) { if (u == T || !maxf) { return maxf; } int cnt = 0; for (int &i = cur[u], tem; i; i = nxt[i]) if (f[i] && lev[to[i]] == lev[u] + 1) { tem = DFS(to[i], min(maxf, f[i])); maxf -= tem; f[i] -= tem; f[i ^ 1] += tem; cnt += tem; if (!maxf) { break; } } if (!cnt) { lev[u] = -1; } return cnt; } ll Dinic(int x) { ll ans = 0; while (BFS(x)) { ans += DFS(S, 2147483647); } return ans; } void init(int SS, int TT) { for (int i = 0; i <= TT; i++) Head[i] = 0; ed = 1; S = SS; T = TT; return; } ll answer = 0; int main() { int n, m; int u, v; ll a, b, c; while (scanf("%d %d", &n, &m) == 2) { answer = 0; init(0, n + 2); for (int i = 1; i <= m; i++) { scanf("%d %d %lld %lld %lld", &u, &v, &a, &b, &c); addedge(S, u, a), addedge(u, v, a + c - 2 * b), addedge(v, T, c); addedge(S, v, a), addedge(v, u, a + c - 2 * b), addedge(u, T, c); answer += 2 * a + 2 * c; } printf("%lld\n", (answer - Dinic(n + 2)) / 2); } return 0; }