Codeforces 588.A Duff and Meat

来源:互联网 发布:留美幼童 知乎 编辑:程序博客网 时间:2024/06/06 07:09

A. Duff and Meat
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly ai kilograms of meat.

There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for pidollars per kilogram. Malek knows all numbers a1, ..., an and p1, ..., pn. In each day, he can buy arbitrary amount of meat, also he can keep some meat he has for the future.

Malek is a little tired from cooking meat, so he asked for your help. Help him to minimize the total money he spends to keep Duff happy for n days.

Input

The first line of input contains integer n (1 ≤ n ≤ 105), the number of days.

In the next n lines, i-th line contains two integers ai and pi (1 ≤ ai, pi ≤ 100), the amount of meat Duff needs and the cost of meat in that day.

Output

Print the minimum money needed to keep Duff happy for n days, in one line.

Examples
input
31 32 23 1
output
10
input
31 32 13 2
output
8
Note

In the first sample case: An optimal way would be to buy 1 kg on the first day, 2 kg on the second day and 3 kg on the third day.

In the second sample case: An optimal way would be to buy 1 kg on the first day and 5 kg (needed meat for the second and third day) on the second day.

    题意:给出每天的肉的需要的量和每天肉的价格,求在n天后所花金额最少。

    分析:该题贪心解决。自上往下遍历,若后几天的肉的价格均大于今天的价格,则今天买完后几天的肉。遍历直到遇到一天价格小于今天的价格再开始一轮遍历。总的n数遍历一次即可,时间复杂度为O(logn)。见AC代码:

#include<stdio.h>const int maxn=100005;int a[maxn],p[maxn];int main(){int n;while(~scanf("%d",&n)){for(int i=0; i<n; i++)scanf("%d%d",&a[i],&p[i]);long long res=0;for(int i=0; i<n; i++){int sum=0,j,s=p[i];//以s保存初始值 因为i会发生月前 导致加上的值发生改变for( j=i; j<n; j++){if(p[j]>=p[i])sum+=a[j];else{i=j-1;break;//break后 i++}}res+=sum*s;if(j==n)//当某个i值一直遍历到最后时  需要将其的值更新为n-1 即退出整个循环i=n-1;}printf("%I64d\n",res);}}
    在书写代码的时候遇到一些问题。贪心循环时i的跳转、变量的区间和值的改变千万需要注意。注意以一个价格遍历至最后时需要更新i的值,要不然会重复计算导致运算出错。

    在书写代码时需要严谨慎重,周全考虑每一步后再书写胜过出错调试。贪心这方面还是需要多敲多练。

    特记下,以备后日回顾。

0 0
原创粉丝点击