【模板】费用流

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值