网络流费用流模板

费用流

#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
#define N 100010
int n,m,s,t;
int head[N],nex[N],e[N],w[N],cost[N],tot;
int d[N],v[N],incf[N],pre[N],maxflow,ans;
void add(int x,int y,int z,int k){
    w[++tot]=z,e[tot]=y,nex[tot]=head[x],head[x]=tot,cost[tot]=k;
    w[++tot]=0,e[tot]=x,nex[tot]=head[y],head[y]=tot,cost[tot]=-k;
}

bool spfa(){
    queue<int>que;
    memset(d,0xcf,sizeof d);
    memset(v,0,sizeof v);
    que.push(s);d[s]=0;v[s]=1;incf[s]=0x3f3f3f3f;
    while(que.size()){
        int x=que.front();que.pop();v[x]=0;
        for(int i=head[x];i;i=nex[i]){
            if(!w[i]) continue;
            int y=e[i];
            if(d[y]<d[x]+cost[i]){
                d[y]=d[x]+cost[i];
                incf[y]=min(incf[x],w[i]);
                pre[y]=i;
                if(!v[y]) v[y]=1,que.push(y);
            }
        }
    }
    if(d[t]==0xcfcfcfcf) return 0;
    return 1;
}

void update(){
    int x=t;
    while(x!=s){
        int i=pre[x];
        w[i]-=incf[t];
        w[i^1]+=incf[t];
        x=e[i^1];
    }
    maxflow+=incf[t];
    ans+=d[t]*incf[t];
}


int main()
{
    cin>>n>>m;
    while(spfa()) update();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值