最小费用最大流模板

#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<set>
#include<map>
#include<stack>
#include<cstring>
#define inf 2147483647
#define ls rt<<1
#define rs rt<<1|1
#define lson ls,nl,mid,l,r
#define rson rs,mid+1,nr,l,r
#define N 100010
#define For(i,a,b) for(int i=a;i<=b;i++)
#define p(a) putchar(a)
#define g() getchar()

using namespace std;
int n,m,s,t,x,y,v,w,maxflow,mincost,tot;
int head[N],pre[N],last[N],flow[N],d[N];
bool vis[N];
struct node{
    int n;
    int v;
    int w;
    int next;
}e[N];
queue<int>q;
void in(int &x){
    int y=1;
    char c=g();x=0;
    while(c<'0'||c>'9'){
        if(c=='-')y=-1;
        c=g();
    }
    while(c<='9'&&c>='0'){
        x=(x<<1)+(x<<3)+c-'0';c=g();
    }
    x*=y;
}
void o(int x){
    if(x<0){
        p('-');
        x=-x;
    }
    if(x>9)o(x/10);
    p(x%10+'0');
}

void push(int x,int y,int v,int w){
    e[tot].n=y;
    e[tot].v=v;
    e[tot].w=w;
    e[tot].next=head[x];
    head[x]=tot++;
}

bool spfa(int s,int t){
    memset(d,0x7f,sizeof(d));
    memset(flow,0x7f,sizeof(flow));
    memset(vis,0,sizeof(vis));
    q.push(s);
    vis[s]=1;
    d[s]=0;
    pre[t]=-1;
    while(!q.empty()){
        int now=q.front();
        q.pop();
        vis[now]=0;
        for(int i=head[now];i!=-1;i=e[i].next)
            if(e[i].v>0&&d[e[i].n]>d[now]+e[i].w){
                d[e[i].n]=d[now]+e[i].w;
                pre[e[i].n]=now;
                last[e[i].n]=i;
                flow[e[i].n]=min(flow[now],e[i].v);
                if(!vis[e[i].n]){
                    vis[e[i].n]=1;
                    q.push(e[i].n);
                }
            }
    }
    return pre[t]!=-1;
}

void MCMF(int s,int t){
    while(spfa(s,t)){
        int now=t;
        maxflow+=flow[t];
        mincost+=flow[t]*d[t];
        while(now!=s){
            e[last[now]].v-=flow[t];
            e[last[now]^1].v+=flow[t];
            now=pre[now];
        }
    }
}

int main(){
    in(n);in(m);in(s);in(t);
    memset(head,-1,sizeof(head));
    For(i,1,m){
        in(x);in(y);in(v);in(w);
        push(x,y,v,w);
        push(y,x,0,-w);
    }
    MCMF(s,t);
    o(maxflow);p(' ');o(mincost);
    return 0;
}

 

posted @ 2019-07-18 20:59  WeiAR  阅读(115)  评论(0编辑  收藏  举报