最大流最小费用流模板

来源:互联网 发布:谷歌seo初级指南2016 编辑:程序博客网 时间:2024/06/06 02:47
#include<cstdio>#include<cstring>#include<iostream>#include<iomanip>#include<queue>#include<cmath>#include<stack>#include<map>#include<vector>#include<set>#include<algorithm>using namespace std;typedef long long LL;const int int_max = 0x07777777;const int int_min = 0x80000000;const int maxn = 5000;struct Edge {    int from,to,cap,flow,cost;    Edge(int _from, int _to, int _cap, int _flow, int _cost):from(_from),to(_to),cap(_cap),flow(_flow),cost(_cost){}};vector<int> g[maxn];vector<Edge> es;int inq[maxn],d[maxn],a[maxn],p[maxn];int s,t,result;void AddEdge(int from, int to, int cap,int flow,int cost){    es.push_back(Edge(from,to,cap,flow,cost));    es.push_back(Edge(to,from,0,0,0-cost));    int num = es.size();    g[from].push_back(num-2);    g[to].push_back(num-1);}void solve(){    memset(a, 0, sizeof(a));    a[s] = int_max;    result = 0;    while(true){        for(int i = 0; i < maxn; i++) d[i] = int_max;        d[s] = 0;        memset(inq, 0, sizeof(inq));        queue<int> q;        q.push(s);        inq[s] = 1;        while(!q.empty()){            int u = q.front();            q.pop();            inq[u] = 0;            for(int i = 0; i < g[u].size(); i++){                Edge& e = es[g[u][i]];                if(e.cap>e.flow && d[e.to] > d[e.from]+e.cost){                    a[e.to] = (a[e.from] > e.cap-e.flow ? e.cap-e.flow : a[e.from]);                    d[e.to] = d[e.from] + e.cost;                    p[e.to] = g[u][i];                    if(!inq[e.to]) {q.push(e.to); inq[e.to] = 1;}                }            }        }        if(d[t]==int_max) break;        result += d[t]*a[t];        int u = t;        while(u!=s){            es[p[u]].flow += a[t];            es[p[u]^1].flow -= a[t];            u = es[p[u]].from;        }    }}

0 0
原创粉丝点击