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 aikilograms 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 pi dollars 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 forn days.
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.
Print the minimum money needed to keep Duff happy for n days, in one line.
3 1 3 2 2 3 1
10
3 1 3 2 1 3 2
8
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.
直接模拟:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAX = 100000+5;
int a[MAX],b[MAX];
int main()
{
int n;
while(scanf("%d", &n) != EOF)
{
for(int i=1;i<=n;i++)
scanf("%d%d",&a[i],&b[i]);
int sum = 0;
for(int i=1;i<=n;i++)
{
int cnt = a[i];
int pos = i;
for(int j=i+1;b[j]>b[i] && j<=n;j++)
{
cnt+=a[j];
pos = j;
}
sum=sum + cnt*b[i];
i = pos ;
}
printf("%d\n", sum);
}
return 0;
}
但是看了解题题报告,发现能优化,时间复杂度为O(N)
int price = MAX;
for(int i=1;i<=n;i++)
{
price = min(price,b[i]);
sum+=price*a[i];
}