POJ2393 Yogurt factory

Description

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.

Input

  • 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.

Output

  • 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.

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.


题解:

思路是贪心。
按一般思路来想。
第一天的奶酪只能当天制作;
第二天的奶酪可以选择当天制作,或者第一天制作;
第三天的奶酪可以选择当天做,或者第一天做,或者第二天做。
这样第n天的奶酪共有n^2/2种选择。

题目的关键条件是:每周生产的多余奶酪,储存价格为“每单位每周S元”。
第一天制作价格为88元。
第二天有2种选择,如果是第二天的奶酪当天制作,每单位为89元,如果是第一天制作的储存下来的奶酪,每单位为88+5元。在两者中取小,可见第二天应该当天制作。
第三天有3种选择,如果第一天制作的奶酪储存下来,每单位为88+5+5,第二天制作的储存下来,每单位为89+5,第三天当天制作,每单位97元。
将上述写成式子:
    第一天:min(88)                
    第二天:min(88+5,89)           
    第三天:min(88+5+5,89+5,97)可见第三天的比较,可在第二天比较结果上化简。
    因为(88+5,89)与(88+5+5,89+5)的比较结果是相同的。
    因此,只要记录每次比较的最优解(用q表示),将其与下一个再进行比较即可。
    
总结:
1、贪心题目时,若遇到需要向前迭代比较的情况,可以考虑上一步的最优解结果是否可以用到下一步。
2、注意题目所给取值范围。本题的最终答案cost必须为longlong,int和long均WA。
#include 
#include 
#define MAX_N 10005

using namespace std;

int C[MAX_N];
int Y[MAX_N];
int S;

int main() {
    int q,N;
    long long cost = 0;
    scanf("%d%d",&N,&S);
    for(int i = 1;i <= N;i++){
        scanf("%d%d",&C[i],&Y[i]);
    }
    
    q = C[1];
    cost = Y[1]*q;
    
    for(int i = 2;i <= N;i++){
        q = min(C[i],q+S);
        cost += Y[i]*q;
    }
    
    printf("%lld\n",cost);
}

你可能感兴趣的:(poj贪心算法)