网络流费用流模板

费用流

#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){
    e[++tot]=z,e[tot]=y,nex[tot]=head[x],head[x]=tot,cost[tot]=k;
    e[++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;
    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;
}
发布了51 篇原创文章 · 获赞 7 · 访问量 1928

猜你喜欢

转载自blog.csdn.net/Fooooooo/article/details/105731218
今日推荐