minCostMaxFlow Template


#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int MAXN = 205;
const int MAXM = MAXN * MAXN;
const int INF = 0x7fffffff;

struct MCMF_{
    int head[MAXN], cnt;
    int pre[MAXN], pos[MAXN];
    int dis[MAXN], que[MAXN * 10];
    bool vis[MAXN];

    struct edge_ {
        int to, vol, cost,next;
    }edge[MAXM];

    void add(int from, int to, int vol, int cost) {
        edge[cnt] = (edge_){to, vol, cost, head[from]};
        head[from] = cnt++;
        edge[cnt] = (edge_){from, 0, -cost, head[to]};
        head[to] = cnt++;
    }

    bool spfa(int s, int t) {
        memset(pre, -1, sizeof(pre));
        memset(vis, 0, sizeof(vis));
        int tl = 0, ft = 1, tp;
        fill(dis, dis + MAXN, INF);
        que[0] = s, pre[s] = s;
        dis[s] = 0, vis[s] = 1;
        while(tl < ft) {
            tp = que[tl++], vis[tp] = 0;
            for(int now = head[tp]; ~now; now = edge[now].next) {
                int adj = edge[now].to;
                if(edge[now].vol > 0 && dis[tp] + edge[now].cost < dis[adj]) {
                    dis[adj] = dis[tp] + edge[now].cost;
                    pre[adj] = tp, pos[adj] = now;
                    if(!vis[adj]) {
                        vis[adj] = 1;
                        que[ft++] = adj;
                    }
                }
            }
        }
        return pre[t] != -1;
    }

    int maxFlow(int s, int t, int &flow) {
        int cost = 0;
        flow = 0;
        while(spfa(s, t)) {
            int f = INF;
            for(int now = t; now != s; now = pre[now])
                if (edge[pos[now]].vol < f)
                    f = edge[pos[now]].vol;
            flow += f, cost += dis[t] * f;
            for(int now = t; now != s; now = pre[now]) {
                edge[pos[now]].vol -= f;
                edge[pos[now] ^ 1].vol += f;
            }
        }
        return cost;
    }
}mcmf;

int main(){

    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值