luogu P4015 运输问题

送分小仙女□ 提交于 2020-02-08 00:05:02

经典问题,货物供需平衡,很容易想到网络流,设源点和汇点,源点对每个仓库连一条capacity为仓库容量的边,cost为0,每个商店对汇点连一条capacity为需要的量的点,cost为0,每一个仓库与商店之间连一条capacity为无限大,cost为给定的边,直接跑最小费用最大流即可,求最大费用就去反边即可

#include<bits/stdc++.h>
using namespace std;
#define lowbit(x) ((x)&(-x))
typedef long long LL;

const int maxm = 3e4+5;
const int INF = 0x3f3f3f3f;

struct edge{
    int u, v, cap, flow, cost, nex;
} edges[maxm];

int head[maxm], cur[maxm], cnt, fa[maxm], d[maxm], n, m, capacity[2][105], flowcost[105][105];
bool inq[maxm];

void init() {
    memset(head, -1, sizeof(head));
}

void addedge(int u, int v, int cap, int cost) {
    edges[cnt] = edge{u, v, cap, 0, cost, head[u]};
    head[u] = cnt++;
}

bool spfa(int s, int t, int &flow, LL &cost) {
    for(int i = 0; i <= n+m+1; ++i) d[i] = INF; //init()
    memset(inq, false, sizeof(inq));
    d[s] = 0, inq[s] = true;
    fa[s] = -1, cur[s] = INF;
    queue<int> q;
    q.push(s);
    while(!q.empty()) {
        int u = q.front();
        q.pop();
        inq[u] = false;
        for(int i = head[u]; i != -1; i = edges[i].nex) {
            edge& now = edges[i];
            int v = now.v;
            if(now.cap > now.flow && d[v] > d[u] + now.cost) {
                d[v] = d[u] + now.cost;
                fa[v] = i;
                cur[v] = min(cur[u], now.cap - now.flow);
                if(!inq[v]) {q.push(v); inq[v] = true;}
            }
        }
    }
    if(d[t] == INF) return false;
    flow += cur[t];
    cost += 1LL*d[t]*cur[t];
    for(int u = t; u != s; u = edges[fa[u]].u) {
        edges[fa[u]].flow += cur[t];
        edges[fa[u]^1].flow -= cur[t];
    }
    return true;
}

int MincostMaxflow(int s, int t, LL &cost) {
    cost = 0;
    int flow = 0;
    while(spfa(s, t, flow, cost));
    return flow;
}

void build_graph(int val, int s, int t) {
    for(int i = 1; i <= m; ++i)
        addedge(s, i, capacity[0][i], 0), addedge(i, s, 0, 0);
    for(int i = 1; i <= n; ++i)
        addedge(m+i, t, capacity[1][i], 0), addedge(t, m+i, 0, 0);
    for(int i = 1; i <= m; ++i)
        for(int j = 1; j <= n; ++j) {
            addedge(i, m+j, INF, flowcost[i][j]*val), addedge(m+j, i, 0, -flowcost[i][j]*val);
        }
}

void run_case() {
    init();
    cin >> m >> n;
    int s = 0, t = m + n + 1;
    for(int i = 1; i <= m; ++i)
        cin >> capacity[0][i];
    for(int i = 1; i <= n; ++i)
        cin >> capacity[1][i];
    for(int i = 1; i <= m; ++i)
        for(int j = 1; j <= n; ++j)
            cin >> flowcost[i][j];
    build_graph(1, s, t);
    LL cost = 0;
    MincostMaxflow(s, t, cost);
    cout << cost << "\n";
    cost = 0;
    init();
    build_graph(-1, s, t);
    MincostMaxflow(s, t, cost);
    cout << -cost;
}

int main() {
    ios::sync_with_stdio(false), cin.tie(0);
    run_case();
    //cout.flush();
    return 0;
}
View Code

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!