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;
}
posted @ 2020-01-17 11:23  白木偶君  阅读(97)  评论(0编辑  收藏  举报