pku2363 Yogurt factory
每周要供应一定数目的奶酪,但是每周的生产成本可能会变化,而存储成本不会变化,问如何生产代价最低。
Sample Input
4 5 88 200 89 400 97 300 91 500
Sample Output
126900
Hint
OUTPUT DETAILS:
In week 1, produce 200 units of yogurt and deliver all of it. In week 2, produce 700 units: deliver 400 units while storing 300 units. In week 3, deliver the 300 units that were stored. In week 4, produce and deliver 500 units.
贪心问题,有可能某周多生产,下周不生产,因为下周的生产成本太大,以至于宁可多存储一天,甚至两天,三天....。
事实上某周多生产,可以还是看成是在下一周生产,只是我们用等价生产成本来看,
本周等价生产成本 = min(上一周的等价生产成本+存储一周的成本, 这周的生产成本)
如果
存储成本为5
第一周生产成本80,第二周86,第三周92
那么其实应该第一周生产完这三周的供应量。相当与第一周等价生产成本80,第二周等价生产成本85,第三周90.随着输入,扫描处理一遍即可得到最优解。
不过下面的程序比较耗时,似乎是用cout,cin的关系,用printf,scanf会快很多。
1 #include <iostream>
2 using namespace std;
3
4 void GetMinCost()
5 {
6 long long cost = 0;
7 int weekNum, makeCost, storeCost, supplyNum;
8 cin >> weekNum >> storeCost;
9 int preMakeCost, minCost;
10 //the first week
11 cin >> makeCost >> supplyNum;
12 cost += makeCost * supplyNum;
13 preMakeCost = makeCost + storeCost;
14 //other weeks
15 for (int i = 1; i < weekNum; i++) {
16 cin >> makeCost >> supplyNum;
17 minCost = min(preMakeCost, makeCost);
18 cost += minCost * supplyNum;
19 preMakeCost = minCost + storeCost;
20 }
21
22 cout << cost << endl;
23 }
24
25 int main(int argc, char *argv[])
26 {
27 GetMinCost();
28 return 0;
29 }
2 using namespace std;
3
4 void GetMinCost()
5 {
6 long long cost = 0;
7 int weekNum, makeCost, storeCost, supplyNum;
8 cin >> weekNum >> storeCost;
9 int preMakeCost, minCost;
10 //the first week
11 cin >> makeCost >> supplyNum;
12 cost += makeCost * supplyNum;
13 preMakeCost = makeCost + storeCost;
14 //other weeks
15 for (int i = 1; i < weekNum; i++) {
16 cin >> makeCost >> supplyNum;
17 minCost = min(preMakeCost, makeCost);
18 cost += minCost * supplyNum;
19 preMakeCost = minCost + storeCost;
20 }
21
22 cout << cost << endl;
23 }
24
25 int main(int argc, char *argv[])
26 {
27 GetMinCost();
28 return 0;
29 }