生活随笔
收集整理的這篇文章主要介紹了
[codevs 1237] 餐巾计划问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
http://codevs.cn/problem/1237/
題解:
引用《24題》:
把每天分為二分圖兩個集合中的頂點Xi,Yi,建立附加源S匯T。
1、從S向每個Xi連一條容量為ri,費用為0的有向邊。
2、從每個Yi向T連一條容量為ri,費用為0的有向邊。
3、從S向每個Yi連一條容量為無窮大,費用為p的有向邊。
4、從每個Xi向Xi+1(i+1<=N)連一條容量為無窮大,費用為0的有向邊。
5、從每個Xi向Yi+m(i+m<=N)連一條容量為無窮大,費用為f的有向邊。
6、從每個Xi向Yi+n(i+n<=N)連一條容量為無窮大,費用為s的有向邊。
求網絡最小費用最大流,費用流值就是要求的最小總花費。
【建模分析】
這個問題的主要約束條件是每天的餐巾夠用,而餐巾的來源可能是最新購買,也可能是前幾天送洗,今天剛剛洗好的餐巾。每天用完的餐巾可以選擇送到快洗部或慢洗部,或者留到下一天再處理。
經過分析可以把每天要用的和用完的分離開處理,建模后就是二分圖。二分圖X集合中頂點Xi表示第i天用完的餐巾,其數量為ri,所以從S向Xi連接容量為ri的邊作為限制。Y集合中每個點Yi則是第i天需要的餐巾,數量為ri,與T連接的邊容量作為限制。每天用完的餐巾可以選擇留到下一天(Xi->Xi+1),不需要花費,送到快洗部(Xi->Yi+m),費用為f,送到慢洗部(Xi->Yi+n),費用為s。每天需要的餐巾除了剛剛洗好的餐巾,還可能是新購買的(S->Yi),費用為p。
在網絡上求出的最小費用最大流,滿足了問題的約束條件(因為在這個圖上最大流一定可以使與T連接的邊全部滿流,其他邊只要有可行流就滿足條件),而且還可以保證總費用最小,就是我們的優化目標。
代碼:
總時間耗費: 2598ms?
總內存耗費: 876B
#include<cstdio>
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;const int maxn = 5000 + 10;
const int INF = 1e9 + 7;struct Edge {int from, to, cap, flow, cost;
};int n, 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 n, price, day1, cost1, day2, cost2;cin >> n >> price >> day1 >> cost1 >> day2 >> cost2;s = 0; t = n + n + 1;for(int i = 1; i <= n; i++) {int need;cin >> need;AddEdge(s, i, need, 0); //neededAddEdge(i+n, t, need, 0); //needAddEdge(s, i+n, INF, price); //buyif(i+day1 <= n) AddEdge(i, i+n+day1, INF, cost1); //fastif(i+day2 <= n) AddEdge(i, i+n+day2, INF, cost2); //slowif(i < n) AddEdge(i, i+1, INF, 0); //delay}cout << MincostMaxflow() << endl;return 0;
}
總結
以上是生活随笔為你收集整理的[codevs 1237] 餐巾计划问题的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。