今天是2017/5/17,DCDCBigBig的第四篇博文
费用流
using namespace std;
struct edge{
int u,v,c,r,next,op;
}a[500001];
int head[500001],vs,vt,n,m,tot=0,flow,cost,x,y,z,u;
void add(int x,int y,int z,int u){
a[++tot].u=x;
a[tot].v=y;
a[tot].r=z;
a[tot].c=u;
a[tot].next=head[x];
head[x]=tot;
a[tot].op=tot+1;
a[++tot].u=y;
a[tot].v=x;
a[tot].r=0;
a[tot].c=-u;
a[tot].next=head[y];
head[y]=tot;
a[tot].op=tot-1;
}
bool spfa(int s,int t,int &flow,int &cost){
int q[1000001],sp[500001],p[500001],b[500001],tmp,u,v,f=1,r=1;
bool isin[300001];
memset(isin,0,sizeof(isin));
memset(sp,0x3f,sizeof(sp));
sp[s]=0;
isin[s]=true;
p[s]=0;
b[s]=1061109567;
q[f]=s;
while(f<=r){
u=q[f];
tmp=head[u];
while(tmp!=-1){
v=a[tmp].v;
if(a[tmp].r>0&&sp[v]>sp[u]+a[tmp].c){
sp[v]=sp[u]+a[tmp].c;
p[v]=tmp;
b[v]=min(b[u],a[tmp].r);
if(!isin[v]){
q[++r]=v;
isin[v]=true;
}
}
tmp=a[tmp].next;
}
f++;
isin[u]=false;
}
if(sp[t]==1061109567)return false;
flow+=b[t];
cost+=sp[t]*b[t];
u=t;
while(u!=s){
a[p[u]].r-=b[t];
a[a[p[u]].op].r+=b[t];
u=a[p[u]].u;
}
return true;
}
int main(){
memset(head,255,sizeof(head));
scanf("%d%d",&n,&m);
vs=1;
vt=n;
for(int i=1;i<=m;i++){
scanf("%d%d%d%d",&x,&y,&z,&u);
add(x,y,z,u);
}
while(spfa(vs,vt,flow,cost));
printf("%d",cost);
return 0;
}
家