自己懒得写网络流用的,你也可以拿去用:
普通最大流:
struct FLOW{
int flow[N],nex[N],first[N],v[N],dep[N],q[N],no[N],num=1,aim,fromt[N];
void add(int from,int to,int val){nex[++num]=first[from];fromt[num]=from;first[from]=num;v[num]=to;flow[num]=val;}
bool bfs(int s,int t){
for(int i=s;i<=t;i++) dep[i]=0,q[i]=0;
q[1]=s;dep[s]=1;no[s]=first[s];
int head=0,tail=1;
while(head!=tail){
int u=q[++head];
for(int i=first[u];i;i=nex[i]){int to=v[i];if(flow[i] && !dep[to]){no[to]=first[to];dep[to] = dep[u] + 1;q[++tail] = to;}}
}
return dep[t]!=0;
}
int dfs(int now,int fl){
if(now==aim) return fl;
int f=0;
for(int i=no[now];i&&fl;i=nex[i]){
no[now]=i;int to=v[i];
if(flow[i] && dep[to] == dep[now]+1){int x=dfs(to,min(fl,flow[i]));flow[i]-=x;flow[i^1]+=x;fl-=x;f+=x; }
}
if(!f) dep[now]=-2;return f;
}
int mxflow(int s,int t){
aim=t;int ret=0;
while(bfs(s,t)) ret+=dfs(s,1<<30);
return ret;
}
}G;
最大费用最大流:
struct FLOW{
int num=1,nex[N],first[N],v[N],flow[N],cost[N],dis[N],inf[N],last[N],vis[N],q[N];
int pre[N],mincost,fromt[N],vib[N];
void add(int from,int to,int val,int c){nex[++num]=first[from];fromt[num]=from;first[from]=num;v[num]=to;flow[num]=val;cost[num]=c;}
bool spfa(int s,int t){
memset(dis,0xcf,sizeof(dis));memset(vis,0,sizeof(vis));memset(inf,0x7f,sizeof(inf));
q[1]=s;vis[s]=1;dis[s]=0;pre[t]=-1;int l=0,r=1;
while(l!=r){int u=q[++l];vis[u]=0;for(int i=first[u];i;i=nex[i]){int to=v[i];if(flow[i] && dis[to]<dis[u]+cost[i]){dis[to]=dis[u]+cost[i];pre[to]=u;last[to]=i;inf[to]=min(inf[u],flow[i]);if(!vis[to]){vis[to]=1;q[++r]=to;}}}}
return pre[t]!=-1;
}
void EK(int s,int t){
while(spfa(s,t)){
int now=t;mincost+=inf[t]*dis[t];
while(now!=s){flow[last[now]]-=inf[t];flow[last[now]^1]+=inf[t];now=pre[now];}
}
}
}G,T;
最小费用最大流:
struct FLOW{
int num=1,nex[N],first[N],v[N],flow[N],cost[N],dis[N],inf[N],last[N],vis[N],q[N];
int pre[N],mincost,fromt[N],vib[N];
void add(int from,int to,int val,int c){nex[++num]=first[from];fromt[num]=from;first[from]=num;v[num]=to;flow[num]=val;cost[num]=c;}
bool spfa(int s,int t){
memset(dis,0x7f,sizeof(dis));memset(vis,0,sizeof(vis));memset(inf,0x7f,sizeof(inf));
q[1]=s;vis[s]=1;dis[s]=0;pre[t]=-1;int l=0,r=1;
while(l!=r){int u=q[++l];vis[u]=0;for(int i=first[u];i;i=nex[i]){int to=v[i];if(flow[i] && dis[to]>dis[u]+cost[i]){dis[to]=dis[u]+cost[i];pre[to]=u;last[to]=i;inf[to]=min(inf[u],flow[i]);if(!vis[to]){vis[to]=1;q[++r]=to;}}}}
return pre[t]!=-1;
}
void EK(int s,int t){
while(spfa(s,t)){
int now=t;mincost+=inf[t]*dis[t];
while(now!=s){flow[last[now]]-=inf[t];flow[last[now]^1]+=inf[t];now=pre[now];}
}
}
}G,T;