1.题目链接。第一问就是最大流,第二问也是比较套路,新建一个超级源点和起点相连,限流为k,费用为0,其他边的容量设置为大于k的数,然后从超级源点求MCMF即可。写这个题,主要是为了复习一下网络流,手写一遍MCMF。
#include<bits/stdc++.h>
using namespace std;
const int maxn=5010*4;
const int inf=1e9;
queue <int> q;
int n,m,k,maxflow,mincost;
struct Edge{
int next,to,flow,dis;
}edge[maxn];
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(){
scanf("%d%d%d",&n,&m,&k);
memset(head,-1,sizeof(head));
for(int i=0;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(1, n);
int ans1=maxflow;
tot=0;
for(int i=0;i<m;i++){
add(x[i],y[i],k+100,f[i]);
}
add(0,1,k,0);
MCMF(0,n);
printf("%d %d",ans1,mincost);
}