关闭

minCostMaxFlow Template

332人阅读 评论(0) 收藏 举报
分类:


#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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:29517次
    • 积分:922
    • 等级:
    • 排名:千里之外
    • 原创:65篇
    • 转载:2篇
    • 译文:0篇
    • 评论:4条
    最新评论