传送门
第一问最大流,在建图的过程中把费用设为0
第二问把边重新再原图上连一遍,容量为inf(实际上为k就可以),费用为输入,设置新的源点向原来的源点之间连边,容量为k、费用为0;这样再跑最小费用最大流的时候就会优先经过残留网络的边(因为其费用为0)因此求出来的就是最小扩容费用
#include
#include
#include
#include
#include
using namespace std;
const int maxn=1000001;
const int inf=1e9;
queue <int> q;
int n,m,k,maxflow,mincost;
struct Edge{
int next,to,flow,dis;
}edge[maxn<<1];
int num_edge=-1,head[maxn],last[maxn],pre[maxn],dis[maxn],flow[maxn];
int bian[maxn],tot;
int x[maxn],y[maxn],z[maxn],f[maxn];
void add_edge(int from,int to,int flow,int dis)
{
edge[++num_edge].next=head[from];
edge[num_edge].dis=dis;
edge[num_edge].flow=flow;
edge[num_edge].to=to;
head[from]=num_edge;
}
void add(int x,int y,int z,int f) {add_edge(x,y,z,f); add_edge(y,x,0,-f);}
bool vis[maxn];
bool spfa(int s,int t)
{
memset(dis,0x7f,sizeof(dis));
memset(flow,0x7f,sizeof(flow));
memset(vis,0,sizeof(vis));
while (!q.empty()) q.pop();
q.push(s); vis[s]=1; dis[s]=0; pre[t]=-1;
while (!q.empty())
{
int now=q.front(); q.pop();
vis[now]=0;
for (int i=head[now]; i!=-1; i=edge[i].next)
{
int to=edge[i].to;
if (edge[i].flow>0 && dis[to]>dis[now]+edge[i].dis)
{
dis[to]=dis[now]+edge[i].dis;
flow[to]=min(flow[now],edge[i].flow);
last[to]=i;
pre[to]=now;
if (!vis[to])
{
q.push(to); vis[s]=1;
}
}
}
}
return pre[t]!=-1;
}
void MCMF(int s,int t)
{
while (spfa(s,t))
{
int now=t;
maxflow+=flow[t];
mincost+=dis[t]*flow[t];
while (now!=s)
{
bian[++tot]=last[now];
edge[last[now]].flow-=flow[t];
edge[last[now]^1].flow+=flow[t];
now=pre[now];
}
}
}
int main()
{
memset(head,-1,sizeof(head));
scanf("%d%d%d",&n,&m,&k);
int S=1,T=n;
for (int i=1; i<=m; i++)
{
scanf("%d%d%d%d",&x[i],&y[i],&z[i],&f[i]);
add(x[i],y[i],z[i],0);
}
MCMF(S,T);
printf("%d ",maxflow); maxflow=0; mincost=0;
S=0; add(0,1,k,0);
for (int i=1; i<=m; i++)
add(x[i],y[i],inf,f[i]);
MCMF(S,T);
printf("%d",mincost);
return 0;
}
注意逆向思维;
总结残余网络的应用,可以搞一些事情——输出方案,在原图中加边、求最小扩容费用等