structEdge { int to, next, w; } e[maxm * 2]; int c1, head[maxn]; inlinevoidadd_edge(int u, int v, int w){ e[c1].to = v; e[c1].w = w; e[c1].next = head[u]; head[u] = c1++; }
inlinevoidAdd_edge(int u, int v, int w){ add_edge(u, v, w); add_edge(v, u, 0); }
int dep[maxn], s, t; boolbfs(){ queue<int> Q; Q.push(s); fill(dep, dep + maxn, 0); dep[s] = 1; while (!Q.empty()) { int u = Q.front(); Q.pop(); for (int i = head[u]; ~i; i = e[i].next) { int v = e[i].to, w = e[i].w; if (w > 0 && !dep[v]) { dep[v] = dep[u] + 1; Q.push(v); if (v == t) return1; } } } return0; }
intdfs(int u, int _w){ if (!_w || u == t) return _w; int s = 0; for (int i = head[u]; ~i; i = e[i].next) { int v = e[i].to, w = e[i].w; if (w > 0 && dep[v] == dep[u] + 1) { int di = dfs(v, min(_w - s, w)); e[i].w -= di; e[i ^ 1].w += di; s += di; if (s == _w) break; } } if (s < _w) dep[u] = 0; return s; }
int mf; intdinic(){ while (bfs()) mf += dfs(s, INF); return mf; }
structEdge { int to, next, w, fi; } e[maxm * 2]; int c1, head[maxn]; inlinevoidadd_edge(int u, int v, int w, int fi){ e[c1].to = v; e[c1].w = w; e[c1].fi = fi; e[c1].next = head[u]; head[u] = c1++; }
inlinevoidAdd_edge(int u, int v, int w, int fi){ add_edge(u, v, w, fi); add_edge(v, u, 0, -fi); }
bool vis[maxn]; int dis[maxn], s, t; boolspfa(){ queue<int> Q; Q.push(s); fill(vis, vis + maxn, 0); vis[s] = 1; fill(dis, dis + maxn, INF); dis[s] = 0; while (!Q.empty()) { int u = Q.front(); Q.pop(); vis[u] = 0; for (int i = head[u]; ~i; i = e[i].next) { int v = e[i].to, w = e[i].w, fi = e[i].fi; if (w > 0 && dis[v] > dis[u] + fi) { dis[v] = dis[u] + fi; if (vis[v]) continue; vis[v] = 1; Q.push(v); } } } return dis[t] != INF; }
bool ins[maxn]; int mf, mc; intdfs(int u, int _w){ if (!_w || u == t) return _w; int s = 0; ins[u] = 1; for (int i = head[u]; ~i; i = e[i].next) { int v = e[i].to, w = e[i].w, fi = e[i].fi; if (!ins[v] && w > 0 && dis[v] == dis[u] + fi) { int di = dfs(v, min(_w - s, w)); e[i].w -= di; e[i ^ 1].w += di; s += di; mc += di * fi; if (s == _w) break; } } if (s < _w) dis[u] = INF; ins[u] = 0; return s; }
voidmcmf(){ mf = mc = 0; while (spfa()) mf += dfs(s, INF); }