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
| template <typename cost_t> struct MinCostMaxFlow {
const cost_t INF = std::numeric_limits<cost_t>::max() / 2; int h[maxn], e[maxm], ne[maxm], idx; cost_t f[maxm], w[maxm], d[maxn], incf[maxn]; int q[maxn], pre[maxn]; bool vis[maxn]; int V, S, T;
void init(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, cost_t d) { e[idx] = b, f[idx] = c, w[idx] = d, ne[idx] = h[a], h[a] = idx++; e[idx] = a, f[idx] = 0, w[idx] = -d, ne[idx] = h[b], h[b] = idx++; }
bool spfa() { int hh = 0, tt = 0; for (int i = 0; i <= V; i++) { d[i] = INF; incf[i] = 0; vis[i] = 0; } q[tt++] = S, d[S] = 0, incf[S] = INF; while (hh != tt) { int t = q[hh++]; if (hh == maxn) hh = 0; vis[t] = 0; for (int i = h[t]; ~i; i = ne[i]) { int j = e[i]; if (f[i] && d[j] > d[t] + w[i]) { d[j] = d[t] + w[i]; incf[j] = std::min(incf[t], f[i]); pre[j] = i; if (!vis[j]) { vis[j] = 1; q[tt++] = j; if (tt == maxn) tt = 0; } } } } return incf[T] > 0; }
std::pair<cost_t, cost_t> EK() { cost_t flow = 0, cost = 0; while (spfa()) { cost_t t = incf[T]; flow += t, cost += d[T] * t; for (int i = T; i != S; i = e[pre[i] ^ 1]) { f[pre[i]] -= t, f[pre[i] ^ 1] += t; } } return {flow, cost}; } };
|