zoukankan      html  css  js  c++  java
  • luogu P3381 【模板】最小费用最大流 |网络流费用流

    题目描述

    如题,给出一个网络图,以及其源点和汇点,每条边已知其最大流量和单位流量费用,求出其网络最大流和在最大流情况下的最小费用。

    输入格式

    第一行包含四个正整数N、M、S、T,分别表示点的个数、有向边的个数、源点序号、汇点序号。

    接下来M行每行包含四个正整数ui、vi、wi、fi,表示第i条有向边从ui出发,到达vi,边权为wi(即该边最大流量为wi),单位流量的费用为fi。

    输出格式

    一行,包含两个整数,依次为最大流量和在最大流量情况下的最小费用。


    #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;
    }
    
  • 相关阅读:
    Codeforces 1368F
    Codeforces 1364C
    Hiho1422 Harmonic Matrix Counter (高斯消元)
    Codeforces 19D
    P3164 [CQOI2014]和谐矩阵(高斯消元 + bitset)
    P4254 [JSOI2008]Blue Mary开公司 (李超树)
    P4755 Beautiful Pair (分治 + 主席树)
    P4587 [FJOI2016]神秘数(主席树)
    分布式锁实现,与分布式定时任务
    redis应用场景,缓存的各种问题
  • 原文地址:https://www.cnblogs.com/naruto-mzx/p/12204915.html
Copyright © 2011-2022 走看看