[codevs 1914] 运输问题

来源:互联网 发布:围棋定式软件 编辑:程序博客网 时间:2024/05/17 12:49

[codevs 1914] 运输问题


题解:

直接看要求建图,求费用流取相反数输出,再改边费用求费用流输出。


代码:


总时间耗费: 58ms 
总内存耗费: 364B

#include<cstdio>#include<iostream>#include<vector>#include<queue>#include<algorithm>using namespace std;const int maxn = 500 + 10;const int INF = 1e9 + 7;struct Edge {int from, to, cap, flow, cost;};int s, t;vector<int> G[maxn];vector<Edge> edges;void AddEdge(int from, int to, int cap, int cost) {edges.push_back((Edge){from, to, cap, 0, cost});edges.push_back((Edge){to, from, 0, 0, -cost});int m = edges.size();G[from].push_back(m-2);G[to].push_back(m-1);}int d[maxn], p[maxn], a[maxn];bool inq[maxn];bool BellmanFord(int& cost) {memset(inq, 0, sizeof(inq));for(int i = s; i <= t; i++) d[i] = INF;d[s] = 0; inq[s] = 1; p[s] = 0; a[s] = INF;queue<int> Q;Q.push(s);while(!Q.empty()) {int x = Q.front(); Q.pop();inq[x] = 0;for(int i = 0; i < G[x].size(); i++) {Edge& e = edges[G[x][i]];if(e.cap > e.flow && d[e.to] > d[x] + e.cost) {d[e.to] = d[x] + e.cost;a[e.to] = min(a[x], e.cap-e.flow);p[e.to] = G[x][i];if(!inq[e.to]) { Q.push(e.to); inq[e.to] = 1; }}}}if(d[t] == INF) return 0;cost += d[t]*a[t];int x = t;while(x != s) {edges[p[x]].flow += a[t];edges[p[x]^1].flow -= a[t];x = edges[p[x]].from;}return 1;}int MincostMaxflow() {int cost = 0;while(BellmanFord(cost));return cost;}int main() {int m, n;cin >> m >> n;s = 0; t = m + n + 1;for(int i = 1; i <= m; i++) {int cap; cin >> cap;AddEdge(s, i, cap, 0);}for(int i = m+1; i <= m+n; i++) {int cap; cin >> cap;AddEdge(i, t, cap, 0);}for(int i = 1; i <= m; i++)for(int j = m+1; j <= m+n; j++) {int cost; cin >> cost;AddEdge(i, j, INF, cost);}cout << MincostMaxflow() << endl;for(int i = 0; i < edges.size(); i++) {Edge& e = edges[i];e.flow = 0; e.cost = -e.cost;}cout << -MincostMaxflow() << endl;return 0;}


0 0
原创粉丝点击