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
| template <typename cost_t> struct MaxFlow {
const cost_t INF = std::numeric_limits<cost_t>::max() / 2; int h[maxn], e[maxm], ne[maxm], idx; cost_t f[maxm], incf[maxn]; int q[maxn], cur[maxn]; int V, S, T;
MaxFlow(int v, int s, int t) { for (int i = 0; i <= v; i++) h[i] = -1; idx = 0; V = v, S = s, T = t; }
void add(int a, int b, cost_t c) { e[idx] = b, f[idx] = c, ne[idx] = h[a], h[a] = idx++; e[idx] = a, f[idx] = 0, ne[idx] = h[b], h[b] = idx++; }
bool bfs() { int hh = 0, tt = 0; for (int i = 0; i <= V; i++) { incf[i] = -1; } q[0] = S, incf[S] = 0, cur[S] = h[S]; while (hh <= tt) { int t = q[hh++]; for (int i = h[t]; ~i; i = ne[i]) { int ver = e[i]; if (incf[ver] == -1 && f[i]) { incf[ver] = incf[t] + 1; cur[ver] = h[ver]; if (ver == T) { return true; } q[++tt] = ver; } } } return false; }
cost_t find(int u, cost_t limit) { if (u == T) { return limit; } cost_t flow = 0; for (int i = cur[u]; ~i && flow < limit; i = ne[i]) { cur[u] = i; int ver = e[i]; if (incf[ver] == incf[u] + 1 && f[i]) { cost_t t = find(ver, std::min(f[i], limit - flow)); if (!t) { incf[ver] = -1; } f[i] -= t, f[i ^ 1] += t, flow += t; } } return flow; }
cost_t dinic() { cost_t res = 0, flow = 0; while (bfs()) { while (flow = find(S, INF)) { res += flow; } } return res; } };
|