思路
简单的费用流问题,跑出第一问后在残量网络上加边求最小费用即可
代码
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
const int MAXN = 4000;
const int MAXM = 10000;
const int INF = 0x3f3f3f3f;
struct Edge{
int u,v,cap,cost,flow;
};
struct data{
int u,v,c,w;
}E[MAXM];
int s,t,n,m,k;
vector<Edge> edges;
vector<int> G[MAXN];
void addedge(int u,int v,int cap,int cost){
edges.push_back((Edge){u,v,cap,cost,0});
edges.push_back((Edge){v,u,0,-cost,0});
int cnt=edges.size();
G[u].push_back(cnt-2);
G[v].push_back(cnt-1);
}
int a[MAXN],d[MAXN],p[MAXN],vis[MAXN];
queue<int> q;
bool SPFA(int &flow,int &cost){
memset(d,0x3f,sizeof(d));
memset(p,0,sizeof(p));
q.push(s);
vis[s]=true;
a[s]=INF;
d[s]=0;
while(!q.empty()){
int x=q.front();
q.pop();
vis[x]=false;
for(int i=0;i<G[x].size();i++){
Edge &e = edges[G[x][i]];
if(e.cap>e.flow&&d[x]+e.cost<d[e.v]){
d[e.v]=d[x]+e.cost;
a[e.v]=min(a[x],e.cap-e.flow);
p[e.v]=G[x][i];
if(!vis[e.v]){
vis[e.v]=true;
q.push(e.v);
}
}
}
}
if(d[t]==INF)
return false;
cost+=d[t]*a[t];
flow+=a[t];
for(int i=t;i!=s;i=edges[p[i]].u){
edges[p[i]].flow+=a[t];
edges[p[i]^1].flow-=a[t];
}
return true;
}
void MCMF(int &flow,int &cost){
flow=0,cost=0;
while(SPFA(flow,cost));
}
int main(){
scanf("%d %d %d",&n,&m,&k);
s=1,t=n;
for(int i=1;i<=m;i++){
scanf("%d %d %d %d",&E[i].u,&E[i].v,&E[i].c,&E[i].w);
addedge(E[i].u,E[i].v,E[i].c,0);
}
int flow=0,cost=0;
MCMF(flow,cost);
printf("%d ",flow);
s=MAXN-2;
addedge(s,1,k,0);
for(int i=1;i<=m;i++){
addedge(E[i].u,E[i].v,INF,E[i].w);
}
MCMF(flow,cost);
printf("%d
",cost);
return 0;
}