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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| #include <stdio.h> #include <string.h> #include <iostream> #include <queue> using namespace std;
const int N = 220, M = 22000, INF = 0x3f3f3f3f;
struct node { int u, v, w, next; } e[M]; int head[N], cur[N], tot = 0; void add(int u, int v, int w) { e[tot] = (node) {u, v, w, head[u]}; head[u] = tot++; e[tot] = (node) {v, u, 0, head[v]}; head[v] = tot++; } int h[N], in[N], n, m, s, t, ss, tt, sflow = 0, tflow = 0; bool bfs(int s, int t) { memset(h, 0, sizeof h); memcpy(cur, head, sizeof cur); queue<int> q; q.push(s); h[s] = 1; while(!q.empty()) { int u = q.front(); q.pop(); for(int i = head[u], v; i != -1; i = e[i].next) { v = e[i].v; if(e[i].w and !h[v]) { h[v] = h[u] + 1; if(v == t) return true; q.push(v); } } } return false; }
int dfs(int u, int low, int t) { if(u == t) return low; int w = low; for(int i = cur[u], v; i != -1; i = e[i].next, cur[u] = i) { v = e[i].v; if(e[i].w and h[v] == h[u] + 1) { int f = dfs(v, min(w, e[i].w), t); e[i].w -= f; e[i^1].w += f; w -= f; if(!w) break; } } return low - w; }
int main() { scanf("%d%d%d%d", &n, &m, &s, &t); ss = 0, tt = n+1; memset(head, -1, sizeof head); for(int i=1, u, v, l, h; i<=m; ++i) { scanf("%d%d%d%d", &u, &v, &l, &h); in[u] -= l; in[v] += l; add(u, v, h-l); } for(int i=1; i<=n; ++i) { if(!in[i]); else if(in[i] > 0) { sflow += in[i]; add(ss, i, in[i]); } else { add(i, tt, -in[i]); } } add(t, s, INF); while(bfs(ss, tt)) tflow += dfs(ss, INF, tt); if(sflow != tflow) { printf("please go home to sleep\n"); return 0; } for(int i = head[ss]; i != -1; i = e[i].next) e[i].w = e[i^1].w = 0; for(int i = head[tt]; i != -1; i = e[i].next) e[i].w = e[i^1].w = 0; int sum = e[--tot].w; e[tot-1].w = e[tot].w = 0; while(bfs(s, t)) sum += dfs(s, INF, t); printf("%d\n", sum); return 0; }
|