码迷,mamicode.com
首页 > 其他好文 > 详细

luogu P3381 【模板】最小费用最大流 |网络流费用流

时间:2020-01-17 11:46:18      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:费用流   --   cpp   signed   operator   nod   ios   while   space   

#include<cmath>
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=1e4+10,M=2e5+10,inf=0x3f3f3f3f;
int n,m,s,t;
int nxt[M],head[N],go[M],edge[M],cost[M],cur[N],tot=1;
inline void add(int u,int v,int o1,int o2){
    nxt[++tot]=head[u],head[u]=tot,go[tot]=v,edge[tot]=o1,cost[tot]=o2;
    nxt[++tot]=head[v],head[v]=tot,go[tot]=u,edge[tot]=0,cost[tot]=-o2;    
}
int dis[N],ret;
bool vis[N];
struct node{
    int u,d;
    bool operator<(const node &rhs)const{
        return d>rhs.d;
    }
};
inline bool spfa(){
    memset(dis,0x3f,sizeof(dis)); 
    std::priority_queue<node>q; 
    q.push((node){s,0}),dis[s]=0;
    while(q.size()){
        int u=q.top().u;
        int d=q.top().d;
        q.pop(); 
        if(d!=dis[u])continue;
        for(int i=head[u];i;i=nxt[i]){
            int v=go[i];
            if(edge[i]&&dis[v]>dis[u]+cost[i]){
                dis[v]=dis[u]+cost[i];
                q.push((node){v,dis[v]});
            }
        }
    }
    return dis[t]!=inf;
}
int dinic(int u,int flow){
    if(u==t)return flow;
    vis[u]=1;
    int rest=flow,k;
    for(int i=head[u];i&&rest;i=nxt[i]){
        int v=go[i];
        if(!vis[v]&&edge[i]&&dis[v]==dis[u]+cost[i]){
            k=dinic(v,min(edge[i],rest));
            if(!k)dis[v]=-1;
            else ret+=k*cost[i],edge[i]-=k,edge[i^1]+=k,rest-=k;
        }
    }
    vis[u]=0;
    return flow-rest;
}
signed main(){
    scanf("%d%d%d%d", &n, &m, &s, &t);
    int u, v, w, c;
    while(m--){
        scanf("%d%d%d%d", &u, &v, &w, &c);
        add(u, v, w, c);
    }
    int flow=0,maxflow=0;
    while(spfa())
    while(flow=dinic(s,inf))maxflow+=flow;
    cout<<maxflow<<' '<<ret<<endl;
}

luogu P3381 【模板】最小费用最大流 |网络流费用流

标签:费用流   --   cpp   signed   operator   nod   ios   while   space   

原文地址:https://www.cnblogs.com/naruto-mzx/p/12204915.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!