Description
Bessie is such a hard-working cow. In fact, she is so focused on maximizing her productivity that she decides to schedule her next N (1 ≤ N ≤ 1,000,000) hours(conveniently labeled 0…N-1) so that she produces as much milk as possible.
Farmer John has a list of M (1 ≤ M ≤ 1,000) possibly overlapping intervals in which he is available for milking. Each interval i has a starting hour (0 ≤ starting_houri ≤ N), an ending hour (starting_houri < ending_houri ≤ N), and a corresponding efficiency (1 ≤ efficiencyi ≤ 1,000,000) which indicates how many gallons of milk that he can get out of
Bessie in that interval. Farmer John starts and stops milking at the beginning of the starting hour and ending hour, respectively. When being milked, Bessie must be milked through an entire interval.
Even Bessie has her limitations, though. After being milked during any interval, she must rest R(1 ≤ R ≤ N) hours before she can start milking again. Given Farmer Johns list of intervals, determine the maximum mount of milk that Bessie can produce in the N hours.
Input
-
Line 1: Three
space-separated integers: N, M, and R -
Lines 2…M+1: Line i+1 describes FJ’s ith milking interval
withthree space-separated integers: starting_houri , ending_houri
, and efficiencyi
Output
- Line 1: The
maximum number of gallons of milk that Bessie can product in the N hours
Sample Input
12 4 2
1 2 8
10 12 19
3 6 24
7 10 31
Sample Output
43
翻译:
贝西是一个如此努力的牛。 实际上,她非常专注于最大程度地提高生产力,因此决定安排下一个N(1≤N≤1,000,000)小时(通常标记为0…N-1),以便尽可能多地生产牛奶。
农夫约翰有一个M(1≤M≤1,000)可能重叠的间隔列表,在该间隔中他可以挤奶。
每个间隔i都有一个开始小时(0≤starting_houri≤N),一个结束小时(starting_houri
<Ending_houri≤N)和相应的效率(1≤efficiencyi≤1,000,000)表示可以从中取出多少加仑牛奶
贝西在这段时间里。
农夫约翰分别在开始时间和结束时间开始和停止挤奶。
题解
相当于每头牛的结束产奶时间增加了休息时间,求不重叠的子集所对应的效率最大值。
先按照开始时间将dp数组从小到大排序,然后ans数组存储到 i 时,效率的最大值。
当前效率的最大值 =( 前一个ans的效率值 + 当前的效率,前一个ans的效率值 )
即 ans[ i ] = max(ans[ i ], ans[ j ] + dp[ i ].k);
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
struct milk{
int s, t, k;
};
int N, M, R;
milk dp[1003];
bool cmp (milk a, milk b) {
if(a.s != b.s)
return a.s < b.s;
return a.t < b.t;
}
int ans[1002];
int main() {
while(scanf("%d%d%d", &N, &M, &R) != EOF){
for (int i = 0; i < M; i++) {
scanf("%d%d%d",&dp[i].s, &dp[i].t, &dp[i].k);
dp[i].t += R;
}
sort(dp, dp + M, cmp);
for (int i = 0; i < M; i++) {
ans[i] = dp[i].k;
}
int MAX = 0;
for (int i = 0; i < M; i++) {
for (int j = i; j >= 0; j--) {
if(dp[i].s >= dp[j].t) {
ans[i] = max(ans[i], ans[j] + dp[i].k);
}
}
MAX = max (ans[i], MAX);
}
printf("%d\n", MAX);
}
}