最大流
int d[N];
bool bfs()
{
static queue<int> q;
memset(d, 0x3c, sizeof d);
d[s] = 1;
q.push(s);
while(!q.empty())
{
int u = q.front(); q.pop();
for(int e=fst[u]; e; e=nxt[e])
{
int v = to[e];
if(!d[v] && c[e])
{
d[v] = d[u]+1;
q.push(v);
}
}
}
}
int dfs(int u, int flow)
{
if(u==t) return flow;
int rest = flow, out;
for(int e=fst[u];e&&rest;e=nxt[e])
{
int v = to[e];
if(d[v]==d[u]+1 && c[e]) //still c[e
{
if(out = dfs(v, min(rest, c[e])))
c[e]-=out, c[e^1]+=out, rest-=out;
else d[v]=0;
}
}
return flow-rest;
}
while(bfs()) ans+=dfs(s, INF);
aE(u,v,c); aE(v,u,0);
最小费用最大流
namespace mfmc
{
int d[N];
bool bfs()
{
static queue<int> q; q.push(s);
static bool inq[N]; memset(inq, 0, sizeof inq); inq[s]=1;
memset(d, 0x3f, sizeof d); d[s]=0;
memset(f, 0x3f, sizeof f);
fa[t]=-1;
while(!q.empty())
{
int u = q.front(); q.pop(); inq[u]=0;
for(int e=fst[u];e;e=nxt[e])
{
int v = to[e];
if(c[e]&&d[v]>d[u]+cost[e])
{
d[v]=d[u]+cost[e];
if(!inq[v]) inq[v]=1, q.push(v);
f[v] = min(f[u], c[e]);
fa[v] = u;
ine[v] = e;
}
}
}
return ~fa[t];
}
int mc,mf;
void run()
{
while(bfs())
{
mc+=d[t]*f[t]; mf+=f[t];
for(int u=t; u^s; u=fa[u]) c[ine[e]]-=f[t], c[ine[u]^1]+=f[t];
}
}
}