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
| const int N = 1e4 + 9; const int M = 1e5 + 9; const int INF = 0x3f3f3f3f;
struct Graph { int cnt; int head[N], cur[N], nxt[M], to[M], flow[M], cost[N]; Graph() { cnt = 1; } inline void add(int u, int v, int w, int c) { ++cnt, nxt[cnt] = head[u], to[cnt] = v, flow[cnt] = w, cost[cnt] = c, head[u] = cnt; ++cnt, nxt[cnt] = head[v], to[cnt] = u, flow[cnt] = 0, cost[cnt] = -c, head[v] = cnt; } } G;
int n, m, S, T, maxflow, mincost; int dis[N], flow[N]; bool inq[N], vis[N]; queue<int> q;
inline bool bfs() { for (int i = 1; i <= n; ++i) dis[i] = INF, inq[i] = false; for (int i = 1; i <= n; ++i) G.cur[i] = G.head[i]; dis[S] = 0; q.push(S), inq[S] = true; while (!q.empty()) { int u = q.front(); q.pop(); inq[u] = false; for (int i = G.head[u]; i; i = G.nxt[i]) { int v = G.to[i]; if (G.flow[i] > 0 && dis[v] > dis[u] + G.cost[i]) { dis[v] = dis[u] + G.cost[i]; if (!inq[v]) q.push(v), inq[v] = true; } } } return dis[T] < INF; }
int dfs(int u, int limit) { if (u == T || !limit) return limit; vis[u] = true; int rest = limit; for (int &i = G.cur[u]; i; i = G.nxt[i]) { int v = G.to[i]; if (vis[v] || dis[v] != dis[u] + G.cost[i] || !G.flow[i]) continue; int rlow = dfs(v, min(G.flow[i], rest)); if (!rlow) dis[v] = -1; mincost += rlow * G.cost[i]; G.flow[i] -= rlow, G.flow[i ^ 1] += rlow; rest -= rlow; if (!rest) break; } vis[u] = false; return limit - rest; }
inline void Dinic() { int rlow; while (bfs()) { while ((now = dfs(S, INF))) maxflow += now; } }
|