1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| bool vis[N]; int n, m, st, ed, d[N], cur[N]; int idx = -1, hd[N], nxt[M], edg[M], wt[M], cst[M]; bool bfs() { for (int i = 1; i <= n; i++) d[i] = inf; d[st] = 0; cur[st] = hd[st]; queue<int> q; q.push(st); while (!q.empty()) { int t = q.front(); q.pop(); vis[t] = false; for (int i = hd[t]; ~i; i = nxt[i]) if (d[t] + cst[i] < d[edg[i]] && wt[i]) { d[edg[i]] = d[t] + cst[i]; cur[edg[i]] = hd[edg[i]]; if (!vis[edg[i]]) { q.push(edg[i]); vis[edg[i]] = true; } } } return d[ed] != inf; } int exploit(int x, int limit) { if (x == ed) return limit; int res = 0; vis[x] = true; for (int i = cur[x]; ~i && res < limit; i = nxt[i]) { cur[x] = i; if (d[edg[i]] == d[x] + cst[i] && wt[i] && !vis[edg[i]]) { int t = exploit(edg[i], min(limit - res, wt[i])); if (!t) d[edg[i]] = inf; res += t; wt[i] -= t; wt[i ^ 1] += t; } } vis[x] = false; return res; } int dinic() { int res = 0, flow; while (bfs()) while (flow = exploit(st, inf)) res += flow * d[ed]; return res; } void add(int a, int b, int c, int d) { nxt[++idx] = hd[a]; hd[a] = idx; edg[idx] = b; wt[idx] = c; cst[idx] = d; } int main() { scanf("%d%d%d%d", &n, &m, &st, &ed); for (int i = 1; i <= n; i++) hd[i] = -1; for (int a, b, c, d; m; m--) { scanf("%d%d%d%d", &a, &b, &c, &d); add(a, b, c, d); add(b, a, 0, -d); } printf("%d", dinic()); return 0; }
|