第一问跑一个最大流就好了。对于第二问,在残余网络上连边。如果u->v有边,则连边容量inf,费用为扩容的费用。最后再新建一个汇点T,从n->T连一条容量为K,费用为0的边以限制容量。然后跑最小费用最大流即可。
AC代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#define inf 1000000000
#define N 40005
using namespace std;
int n,m,gol,tot=1,addflow,fst[N],pnt[N],len[N],cst[N],nxt[N];
int d[N],h[N],u[N],v[N],w[N],e[N],last[N]; bool vis[N];
bool bfs(){
memset(d,-1,sizeof(d)); d[1]=1;
int head=0,tail=1; h[1]=1;
while (head<tail){
int x=h[++head],p;
for (p=fst[x]; p; p=nxt[p]) if (len[p]){
int y=pnt[p];
if (d[y]==-1){ d[y]=d[x]+1; h[++tail]=y; }
}
}
return d[gol]!=-1;
}
int dfs(int x,int rst){
if (x==gol || !rst) return rst; int flow=0,p;
for (p=fst[x]; p; p=nxt[p]) if (len[p]){
int y=pnt[p]; if (d[x]+1!=d[y]) continue;
int tmp=dfs(y,min(rst,len[p])); if (!tmp) continue;
flow+=tmp; len[p]-=tmp;
len[p^1]+=tmp; rst-=tmp; if (!rst) break;
}
if (!flow) d[x]=-1; return flow;
}
void add(int aa,int bb,int cc,int dd){
pnt[++tot]=bb; len[tot]=cc; cst[tot]=dd; nxt[tot]=fst[aa]; fst[aa]=tot;
}
bool spfa(){
int head=0,tail=1,i; d[1]=0; h[1]=1;
for (i=2; i<=gol; i++) d[i]=inf;
while (head!=tail){
head=head%20000+1;
int x=h[head],p; vis[x]=0;
for (p=fst[x]; p; p=nxt[p]) if (len[p]){
int y=pnt[p];
if (d[x]+cst[p]<d[y]){
d[y]=d[x]+cst[p]; last[y]=p;
if (!vis[y]){ vis[y]=1; tail=tail%20000+1; h[tail]=y; }
}
}
}
return d[gol]!=inf;
}
int updata(){
int tmp=inf,sum=0,i;
for (i=gol; i!=1; i=pnt[last[i]^1]) tmp=min(tmp,len[last[i]]);
for (i=gol; i!=1; i=pnt[last[i]^1]){
sum+=tmp*cst[last[i]];
len[last[i]]-=tmp; len[last[i]^1]+=tmp;
}
return sum;
}
int main(){
scanf("%d%d%d",&n,&m,&addflow); int i;
for (i=1; i<=m; i++){
scanf("%d%d%d%d",&u[i],&v[i],&w[i],&e[i]);
add(u[i],v[i],w[i],0); add(v[i],u[i],0,0);
}
int ans=0; gol=n; while (bfs()) ans+=dfs(1,inf); printf("%d ",ans);
for (i=1; i<=m; i++){
add(u[i],v[i],inf,e[i]); add(v[i],u[i],0,-e[i]);
}
ans=0; gol=n+1; add(n,n+1,addflow,0); add(n+1,n,0,0);
while (spfa()) ans+=updata(); printf("%d\n",ans);
return 0;
}
by lych
2016.2.25