最大流
int head[N], ver[N], Next[N], edge[N];
int tot, s, t, n, m;
int d[N], now[N];
void init() {
memset(head, 0, sizeof head);
tot = 1;
}
void add(int u, int v, int w) {
ver[++tot] = v, edge[tot] = w, Next[tot] = head[u], head[u] = tot;
ver[++tot] = u, edge[tot] = 0, Next[tot] = head[v], head[v] = tot;
}
bool bfs() {
memset(d, 0, sizeof d);
queue<int>que;
que.push(s);
d[s] = 1, now[s] = head[s];
while (que.size()) {
int x = que.front();que.pop();
for (int i = head[x];i;i = Next[i]) {
if (edge[i] && !d[ver[i]]) {
que.push(ver[i]);
now[ver[i]] = head[ver[i]];
d[ver[i]] = d[x] + 1;
if (ver[i] == t)return 1;
}
}
}
return 0;
}
int dfs(int x, int flow) {
if (x == t)return flow;
int rest = flow, k, i;
for (i = now[x];i && rest;i = Next[i]) {
if (edge[i] && d[ver[i]] == d[x] + 1) {
k = dfs(ver[i], min(rest, edge[i]));
if (!k)d[ver[i]] = 0;
edge[i] -= k;
edge[i ^ 1] += k;
rest -= k;
}
}
now[x] = i;
return flow - rest;
}
int dinic() {
int flow = 0, maxflow = 0;
while (bfs()) {
while (flow = dfs(s, inf))maxflow += flow;
}
}```
## 费用流
```cpp
int head[N], ver[N], Next[N], edge[N], cost[N];
int tot, s, t, maxflow, ans;
int d[N], now[N], vis[N];
int incf[N], pre[N];
void init() {
memset(head, 0, sizeof head);
tot = 1, ans = 0, maxflow = 0;
}
void add(int u, int v, int w, int c) {
ver[++tot] = v, edge[tot] = w, cost[tot] = c, Next[tot] = head[u], head[u] = tot;
ver[++tot] = u, edge[tot] = 0, cost[tot] = -c, Next[tot] = head[v], head[v] = tot;
}
bool spfa() {
queue<int>que;
memset(d, inf, sizeof d);
memset(vis, 0, sizeof vis);
vis[s] = 1, d[s] = 0, que.push(s);
incf[s] = inf;
while (que.size()) {
int x = que.front();
que.pop();
vis[x] = 0;
for (int i = head[x];i;i = Next[i]) {
if (!edge[i])continue;
int y = ver[i];
if (d[y] > d[x] + cost[i]) {
d[y] = d[x] + cost[i];
pre[y] = i;
incf[y] = min(edge[i], incf[x]);
if (!vis[y])vis[y] = 1, que.push(y);
}
}
}
return !(d[t] == inf);
}
void update() {
int x = t;
maxflow += incf[t];
ans += d[t] * incf[t];
while (x != s) {
int i = pre[x];
edge[i] -= incf[t];
edge[i ^ 1] += incf[t];
x = ver[i ^ 1];
}
}
int solve() {
while (spfa())update();
return ans;
}```