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
| #include <bits/stdc++.h> #define int long long using namespace std; const int N = 52100, INF = (1ll << 31) + 10; int head[N], to[N], ne[N], w[N], idx; int dep[N], cur[N]; void add(int u, int v, int x) { to[idx] = v, ne[idx] = head[u], w[idx] = x, head[u] = idx++; to[idx] = u, ne[idx] = head[v], w[idx] = 0, head[v] = idx++; } bool bfs(int s, int t) { memset(dep, 0, sizeof dep); queue<int> q; q.push(s); dep[s] = 1; while(q.size()) { int u = q.front(); q.pop(); for(int i = head[u]; i != -1; i = ne[i]) { int v = to[i]; if(w[i] && !dep[v]) { dep[v] = dep[u] + 1; q.push(v); } } } return dep[t]; } int dfs(int u, int t, int flow) { if(u == t) return flow; int res = 0; for(int &i = cur[u]; i != -1 && flow; i = ne[i]) { int v = to[i]; if(w[i] && dep[v] == dep[u] + 1) { int f = dfs(v, t, min(flow, w[i])); w[i] -= f; w[i ^ 1] += f; flow -= f; res += f; if(!flow) break; } } return res; } int dinic(int s, int t) { int maxflow = 0; while(bfs(s, t)) { memcpy(cur, head, sizeof head); while (int flow = dfs(s, t, INF)) { maxflow += flow; } } return maxflow; } signed main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); memset(head, -1, sizeof head); int n, m, s, t; cin >> n >> m >> s >> t; for(int i = 1; i <= m; i++) { int u, v, w; cin >> u >> v >> w; add(u, v, w); } cout << dinic(s, t); return 0; }
|