生活随笔
收集整理的這篇文章主要介紹了
[codevs 1914] 运输问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
[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;
}
總結
以上是生活随笔為你收集整理的[codevs 1914] 运输问题的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。