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
| 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], pre[maxn]; bool vis[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++) { vis[i] = 0; } q[0] = S, vis[S] = true, incf[S] = INF; while (hh <= tt) { int t = q[hh++]; for (int i = h[t]; ~i; i = ne[i]) { int ver = e[i]; if (!vis[ver] && f[i]) { vis[ver] = true; incf[ver] = std::min(incf[t], f[i]); pre[ver] = i; if (ver == T) return true; q[++tt] = ver; } } } return false; }
cost_t EK() { cost_t flow = 0; while (bfs()) { flow += incf[T]; for (int i = T; i != S; i = e[pre[i] ^ 1]) { f[pre[i]] -= incf[T], f[pre[i] ^ 1] += incf[T]; } } return flow; } };
|