wiki 1914 运输问题

来源:互联网 发布:我要下载淘宝网购物 编辑:程序博客网 时间:2024/06/02 13:05
#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;const int maxN = 1000;const int INF = 1 << 30;int n,m,s,t,result;int a[maxN],d[maxN],p[maxN],cangku[maxN],shangdian[maxN],inq[maxN],mymap[maxN][maxN];struct Edge {    int from, to, cap, flow, cost;};vector<Edge> es;vector<int> g[maxN];void addedge (int from, int to, int cap, int cost){    es.push_back(Edge{from, to, cap, 0, cost});    es.push_back(Edge{to, from, 0, 0, -cost});    int u = es.size();    g[from].push_back(u-2);    g[to].push_back(u-1);}void init(){    cin >> m >> n;    for(int i = 0; i < m; i++) cin >> cangku[i];    for(int i = 0; i < n; i++) cin >> shangdian[i];    for(int i = 0; i < m; i++){        for(int j = 0; j < n; j++) cin >> mymap[i][j];    }    s = m+n;    t = s+1;    for(int i = 0; i < m; i++){        addedge(s, i, cangku[i], 0);    }    for(int i = 0; i < n; i++) addedge(m+i, t, shangdian[i], 0);    for(int i = 0; i < m; i++){        for(int j = 0; j < n; j++) addedge(i, m+j, INF, mymap[i][j]);    }    result = 0;}void solve(){    memset(a, 0, sizeof(a));    a[s] = INF;    while(true){        for(int i = 0; i < maxN; i++) d[i] = INF;        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]==INF) 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;        }    }}int main(int argc, const char * argv[]){    init();    solve();    cout << result << endl;        es.clear();    for(int i = 0; i < maxN; i++) g[i].clear();    for(int i = 0; i < m; i++){        addedge(s, i, cangku[i], 0);    }    for(int i = 0; i < n; i++) addedge(m+i, t, shangdian[i], 0);    for(int i = 0; i < m; i++){        for(int j = 0; j < n; j++) addedge(i, m+j, INF, -mymap[i][j]);    }    result = 0;    solve();        cout << -result << endl;}

0 0
原创粉丝点击