题目Yogurt factory
描述
The cows have purchased a yogurt factory that makes world-famous Yucky Yogurt. Over the next N (1 <= N <= 10,000) weeks, the price of milk and labor will fluctuate weekly such that it will cost the company C_i (1 <= C_i <= 5,000) cents to produce one unit of yogurt in week i. Yucky's factory, being well-designed, can produce arbitrarily many units of yogurt each week.
Yucky Yogurt owns a warehouse that can store unused yogurt at a constant fee of S (1 <= S <= 100) cents per unit of yogurt per week. Fortuitously, yogurt does not spoil. Yucky Yogurt's warehouse is enormous, so it can hold arbitrarily many units of yogurt.
Yucky wants to find a way to make weekly deliveries of Y_i (0 <= Y_i <= 10,000) units of yogurt to its clientele (Y_i is the delivery quantity in week i). Help Yucky minimize its costs over the entire N-week period. Yogurt produced in week i, as well as any yogurt already in storage, can be used to meet Yucky's demand for that week.
输入
* Line 1: Two space-separated integers, N and S.
* Lines 2..N+1: Line i+1 contains two space-separated integers: C_i and Y_i.
输出
* Line 1: Line 1 contains a single integer: the minimum total cost to satisfy the yogurt schedule. Note that the total might be too large for a 32-bit integer.
样例输入
4 5
88 200
89 400
97 300
91 500
样例输出
126900
提示
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.
思路分析
题目:生产牛奶,卖牛奶,求满足题目要求的最小成本。每日生产牛奶有不同价格,每日储存每个单位的牛奶也有成本。
输入:总天数N,每日存储费用S,接着跟着N行,每一行给出那一天的生产成本和需要数量。
解决方案:贪心算法。首先想到比较自然的方法是,第k天需要的牛奶一定是在第1天到第k天之间生产出来的,因此利用两层for循环,外层遍历每一天i的需求,内层从第1天到i天遍历求以下各项的最小值cost1+S*(i-1),cost2+S*(i-2),...,cost i。但是仔细思考发现内层循环有很多重复的部分,例如:求出第10天的最小成本,那第11天的最小成本只需要比较第10天求得的结果+S和第十一天的成本哪个更小就可以了,不用从第1天再算到第10天。因此建立一个长度为N的最小成本备忘录,从第1天到第N天,第1天只能由当天生产,最小值为cost1,从第二天开始由前一天+S和当天成本的最小值求得,最后将这个最小成本备忘录点乘每一天的需求即可求得结果。
过程中的错误
输出部分提示了Note that the total might be too large for a 32-bit integer.但我没有注意,需要用long long类型保存64-bit整形变量。
AC代码
#include <iostream>
using namespace std;
int main() {
int N = 0;
int S = 0;
long long bestcost[10005] = { 0 };
long long cost[10005] = { 0 };
long long need[10005] = { 0 };
cin >> N >> S;
for (int i = 0; i < N; i++) {
cin >> cost[i] >> need[i];
}
for (int i = 0; i < N; i++) {
if (i == 0) {
bestcost[i] = cost[i];
}
else {
bestcost[i] = min(bestcost[i - 1] + S, cost[i]);
}
}
long long ans = 0;
for (int i = 0; i < N; i++) {
ans += bestcost[i] * need[i];
}
cout << ans;
return 0;
}