动态规划 (区间问题)

本文介绍了一道算法题目,涉及奶牛Bessie的产奶效率优化。Farmer John有一系列可能重叠的挤奶时段,每个时段有特定的效率。在每个时段结束后,奶牛需要休息一定小时数。任务是确定在给定时间内,Bessie能产生的最大牛奶量。通过动态规划策略,将时段排序并比较不同组合以找到最优解。给出的代码实现了这一算法,最终输出最大产奶量。
摘要由CSDN通过智能技术生成

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: NM, 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

题目大意:已知一名奶农的工作时长和奶牛在这段时间的某些时间段的产奶效率,奶农也需要休息呀,他每工作一段时间就要休息一段时间,问他工作的这段时间最大的产奶效率。

很显然这是这道题使用动态规划要节省不少时间,思路:先将这些时间段进行从小到大进行排序,本题我按照的是起始时间排序,然后使用动态规划去做就行。具体实现与解析如下: 

2.测试样例: 

Sample Input

12 4 2
1 2 8
10 12 19
3 6 24
7 10 31

Sample 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风遥~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值