[模版] spfa费用流

在这里插入图片描述

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <vector>
#include <string>
#include <algorithm>
#define INF 0x3f3f3f3f

using namespace std;

typedef long long LL;

const int N = 5010, M = 100010;

int n, m, S, T;
int idx, head[N], e[M], c[M], w[M], ne[M];
int d[N], incf[N], pre[N];
bool vis[N];

void add(int u, int v, int _c, int _w)
{
    e[idx] = v, c[idx] = _c, w[idx] = _w, ne[idx] = head[u], head[u] = idx ++;
    e[idx] = u, c[idx] = 0, w[idx] = - _w, ne[idx] = head[v], head[v] = idx ++;
}

bool spfa()
{
    memset(d, 0x3f, sizeof d);
    memset(incf, 0, sizeof incf);
    queue<int> q;
    q.push(S), vis[S] = true;
    d[S] = 0, incf[S] = INF;
    while(q.size())
    {
        int u = q.front();
        q.pop(), vis[u] = false;

        for(int i = head[u]; ~i; i = ne[i])
        {
            int v = e[i];
            if(c[i] && d[v] > d[u] + w[i])
            {
                d[v] = d[u] + w[i];
                incf[v] = min(incf[u], c[i]);
                pre[v] = i;
                if(!vis[v]) q.push(v), vis[v] = true;
            }
        }
    }
    return incf[T] > 0;
}

void EK(int &flow, int &cost)
{
    flow = cost = 0;
    while(spfa())
    {
        int t = incf[T];
        flow += t, cost += t * d[T];
        for(int i = T; i != S; i = e[pre[i] ^ 1])
            c[pre[i]] -= t, c[pre[i] ^ 1] += t;
    }
}

int main()
{
#ifdef LOCAL
    freopen("in.in", "r", stdin);
    freopen("out.out", "w", stdout);
#endif

    scanf("%d%d%d%d", &n, &m, &S, &T);
    
    memset(head, -1, sizeof head);
    while(m --)
    {
        int u, v, c, w;
        scanf("%d%d%d%d", &u, &v, &c, &w);
        add(u, v, c, w);
    }

    int flow, cost;
    EK(flow, cost);

    printf("%d %d\n", flow, cost);

    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值