acwing-2174. 费用流(最小费用最大流)

给定一个包含 n 个点 m 条边的有向图,并给定每条边的容量和费用,边的容量非负。

图中可能存在重边和自环,保证费用不会存在负环。

求从 S 到 T 的最大流,以及在流量最大时的最小费用。

输入格式
第一行包含四个整数 n,m,S,T。

接下来 m 行,每行三个整数 u,v,c,w,表示从点 u 到点 v 存在一条有向边,容量为 c,费用为 w。

点的编号从 1 到 n。

输出格式
输出点 S 到点 T 的最大流和流量最大时的最小费用。

如果从点 S 无法到达点 T 则输出 0 0。

数据范围
2≤n≤5000,
1≤m≤50000,
0≤c≤100,
−100≤w≤100
S≠T

输入样例:
5 5 1 5
1 4 10 5
4 5 5 10
4 2 12 5
2 5 10 15
1 5 10 10
输出样例:
20 300
#include<bits/stdc++.h>
using namespace std;
const int N = 5010, M = 2 * 100010;
const int INF = 1e8;
struct Edge{
    int v,next,w,f;
}edge[M];
int n,m,s,e;
int head[N],cnt;
void add(int u,int v,int f,int w){
    edge[cnt].v = v;
    edge[cnt].f = f;
    edge[cnt].w = w;
    edge[cnt].next = head[u];
    head[u] = cnt ++;
}
int d[N],q[N],hh = 0,tt = 0,pre[N],curf[N],st[N];
bool spfa(){        //最大流最大费用的话就求最长路即可
    memset(d,0x3f,sizeof d);
    memset(curf,0,sizeof curf);
    memset(st,0,sizeof st);
    hh = tt = 0;
    d[s] = 0,q[tt ++] = s,curf[s] = INF;
    st[s] = true;
    while(hh != tt){
        int t = q[hh ++];
        if(hh == N)hh = 0;
        st[t] = false;
        for(int i = head[t];~i;i = edge[i].next){
            int v = edge[i].v,w = edge[i].w;
            if(edge[i].f && d[v] > d[t] + w){
                d[v] = d[t] + w;
                pre[v] = i;
                curf[v] = min(edge[i].f,curf[t]);
                if(!st[v]){
                    q[tt ++] = v;
                    if(tt == N)tt = 0;
                    st[v] = true;
                }
            }
        }
    }
    return curf[e] > 0;
}
void EK(int &flow,int &cost){
    flow = cost = 0;
    while(spfa()){
        int t = curf[e];
        flow += t;cost += t * d[e];
        for(int i = e;i != s;i = edge[pre[i] ^ 1].v){
            edge[pre[i]].f -= t,edge[pre[i] ^ 1].f += t;
        }
    }
}
int main(){
    cin>>n>>m>>s>>e;
    int x,y,f,w;
    memset(head,-1,sizeof head);
    for(int i = 0;i < m;i ++){
        scanf("%d %d %d %d",&x,&y,&f,&w);
        add(x,y,f,w),add(y,x,0,-w);
    }
    int flow = 0,cost = 0;
    EK(flow,cost);
    printf("%d %d",flow,cost);
    return 0;
}

版权声明:本文为m0_46656833原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。