Valera loves his garden, where n fruit trees grow.
This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai + 1 (all fruits that are not collected in these two days, become unfit to eat).
Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more thanv fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well?
The first line contains two space-separated integers n and v (1 ≤ n, v ≤ 3000) — the number of fruit trees in the garden and the number of fruits that Valera can collect in a day.
Next n lines contain the description of trees in the garden. The i-th line contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ 3000) — the day the fruits ripen on the i-th tree and the number of fruits on the i-th tree.
Print a single integer — the maximum number of fruit that Valera can collect.
2 3 1 5 2 3
8
5 10 3 20 2 20 1 20 4 20 5 20
60
In the first sample, in order to obtain the optimal answer, you should act as follows.
- On the first day collect 3 fruits from the 1-st tree.
- On the second day collect 1 fruit from the 2-nd tree and 2 fruits from the 1-st tree.
- On the third day collect the remaining fruits from the 2-nd tree.
In the second sample, you can only collect 60 fruits, the remaining fruit will simply wither.
题意:
给出 n,m(1 ~ 3000),代表有 n 颗树,每天最大的收获量是 m 。后给出 n 颗树,每颗树都有一个 a 和 b,代表果实成熟时间和总果实数,只有当天数在 a 或者 a + 1 的时候才能摘取果实。问最大的果实收获量是多少。
思路:
贪心。可能同一时间有多颗树成熟的可能,所以用数组 app 保存每天的总果实量,那么在某一天能取的果实数就是 t 与 t - 1 时候的果实。先去 t - 1 天的,若不够 m ,则再去 t 天取,每次都最大填充量去取就行了。错误犯在不应该是循环到 3000 天,应该是要到 3001 天。
AC:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int app[3005];
int main() {
memset(app, 0, sizeof(app));
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i) {
int a, b;
scanf("%d%d", &a, &b);
app[a] += b;
}
int sum = 0;
for (int i = 1; i <= 3001; ++i) {
int left = m;
if (app[i - 1] >= left) {
sum += left;
app[i - 1] -= left;
left = 0;
} else if (app[i - 1]) {
left -= app[i - 1];
sum += app[i - 1];
app[i - 1] = 0;
}
if (left) {
if (app[i] >= left) {
sum += left;
app[i] -= left;
} else if (app[i]) {
sum += app[i];
app[i] = 0;
left = 0;
}
}
}
printf("%d\n", sum);
return 0;
}