【模板】费用流

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#define inf 0x7fffffff
using namespace std;
const int M=1005,N=105;
struct E{int to,cap,flow,cost,nxt;}edge[M*2];
int tot=2,idx[N];
int flow,cost;
int n,m,s,t;
int last[N],edges[N],dis[N],cnt[N];
bool vis[N];
queue<int>q;
void addedge(int from,int to,int cap,int flow,int cost){
    edge[tot].to=to;edge[tot].cap=cap;edge[tot].flow=flow;
    edge[tot].cost=cost;edge[tot].nxt=idx[from];idx[from]=tot++;
}
bool SPFA(){
    q.push(s);
    memset(vis,0,sizeof(vis));
    memset(dis,127,sizeof(dis));
    memset(last,255,sizeof(last));
    memset(cnt,0,sizeof(cnt));
    vis[s]=1;dis[s]=0;
    while(!q.empty()){
        int x=q.front();q.pop();vis[x]=0;
        for(int t=idx[x];t;t=edge[t].nxt){
            E e=edge[t];
            if(e.cap<=e.flow) continue;
            if(dis[e.to]>dis[x]+e.cost){
                last[e.to]=x;
                edges[e.to]=t;
                dis[e.to]=dis[x]+e.cost;
                if(!vis[e.to]) {vis[e.to]=1;q.push(e.to);}
            }
        }
    }
    return (dis[t]!=dis[0]);
}
int main(){
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
    scanf("%d%d%d%d",&n,&m,&s,&t);
    for(int i=1;i<=m;i++){
        int u,v,cap,cost;
        scanf("%d%d%d%d",&u,&v,&cap,&cost);
        addedge(u,v,cap,0,cost);
        addedge(v,u,0,0,-cost);
    }
    flow=0;cost=0;
    while(SPFA()){
        int u=t,f=inf;
        while(last[u]!=-1){
            f=min(edge[edges[u]].cap-edge[edges[u]].flow,f);
            u=last[u];
        }
        u=t;
        while(last[u]!=-1){
            edge[edges[u]].flow+=f;
            edge[edges[u]^1].flow-=f;
            u=last[u];
        }   
// printf("***%d",f);
        flow+=f;
        cost+=dis[t]*f;
    }
    printf("%d\n",cost);
    return 0;
}

你可能感兴趣的:(模板,费用流)