1、题目引入:
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 amount 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 efficiencyiOutput
* Line 1: The maximum number of gallons of milk that Bessie can product in the N hours
题目大意:已知一名奶农的工作时长和奶牛在这段时间的某些时间段的产奶效率,奶农也需要休息呀,他每工作一段时间就要休息一段时间,问他工作的这段时间最大的产奶效率。
很显然这是这道题使用动态规划要节省不少时间,思路:先将这些时间段进行从小到大进行排序,本题我按照的是起始时间排序,然后使用动态规划去做就行。具体实现与解析如下:
2.测试样例:
Sample Input
12 4 2 1 2 8 10 12 19 3 6 24 7 10 31Sample Output
43
3.代码如下:
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
int n,m,r;
const int maxn=1e3+10;
long long dp[maxn];
struct dd
{
int s,e,f;
}d[maxn];
bool cmp(dd x,dd y)
{
if(x.s==y.s) return x.e<y.e;
return x.s<y.s;
}
int main()
{
scanf("%d%d%d",&n,&m,&r);
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&d[i].s,&d[i].e,&d[i].f);
}
sort(d+1,d+1+m,cmp);
memset(dp,0,sizeof(dp));
int ans=0;
for(int i=1;i<=m;i++)
{
dp[i]=d[i].f; //定义边界,因每次进去第一次就需要当前值与前面序列+当前值进行比较,dp起始时为所在位置的值
}
for(int i=1;i<=m;i++) //工作的区间数
{
for(int j=1;j<=i;j++) //i前面面可选的区间
{
if(d[j].e+r<=d[i].s) //如果前面的区间加上休息数小于等于前面区间的起始数则符合要求
{
dp[i]=max(dp[i],dp[j]+d[i].f); //i,与i前区间的效率中取最大值即可
}
}
if(ans<dp[i]) //取最大值
{
ans=dp[i];
}
}
printf("%d\n",ans);
return 0;
}