1. 程式人生 > >貪心演算法HURUST題目

貪心演算法HURUST題目

題目描述:

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.

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

-----------------------
這道題是我在HURBST做的題目,連結是https://vjudge.net/contest/262212#problem/D

中文理解:有一個酸乳酪生產商,每一個星期都有其需求量和價格量,乳酪可以儲存到下個星期使用,不過有儲存費用,此題目要求你找出最小費用的解;

個人看法:這道題目是貪心的基礎題目,它滿足了貪心演算法的基於當前是最優解,找出下一個最優解,保證這一步是最優解。

 1 #include<stdio.h>
 2
#include<algorithm> 3 #include<math.h> 4 #include<vector> 5 #include<iterator> 6 #include<string> 7 #include<string.h> 8 #include<ctype.h> 9 #include<map> 10 #include<stack> 11 #include<queue> 12 #include<iostream> 13 #include<time.h> 14 15 using namespace std; 16 17 #define rep(i ,a, b) for(int i = a; i <= b; i++) 18 #define per(i, a, b) for(int i = a; i <= b; i--) 19 typedef long long ll;//資料量大,用longlong來進行運算較合適。不然會資料溢位。 20 21 struct milk 22 { 23 ll c_i, y_i, id; 24 }a[10006]; 25 26 ll findmin(ll n, ll s) 27 { 28 ll ans=a[0].c_i*a[0].y_i, k = 0; 29 for(ll i = 1; i < n; i++) 30 { 31 ll temp = a[k].c_i+s*(i- a[k].id), cur = a[i].c_i;//記錄前一週牛奶的價格和這個一週的價格,進行比較然後,選取較小的作為當前的最小解; 32 if(temp < cur) 33 { 34 ans += temp*a[i].y_i; 35 } 36 else 37 { 38 ans += cur*a[i].y_i; 39 k = i; 40 } 41 } 42 return ans; 43 } 44 45 int main()//這是貪心問題。 46 { 47 ll n, s; 48 while(scanf("%lld%lld", &n, &s) != EOF) 49 { 50 for(ll i =0; i < n; i++) 51 { 52 scanf("%lld%lld", &a[i].c_i, &a[i].y_i); 53 a[i].id = i; 54 } 55 printf("%lld\n", findmin(n, s)); 56 } 57 return 0; 58 }
View Code