第五周总结
一、知识总结
动态规划还没做太多,但从例题和做的几个题来看,动态规划最核心也最难的是状态转移方程的确定。开始的那一课我还认为动态规划要好好适应枚举过程,事实证明错了。动态规划常用的dp数组的每一维,每个数代表的意义都不同dp[i][j]与
dp[i-1][j]并不是简单的二维数组那样同列不同行的比较。而且目前我看到的题目都牵扯最值的问题,都要用到max,min。再有就是题目给的数极限会很大,先用#define宏定义字母代表数极限大小,会有利于运算,因为我直接在开数组是[100000000000]
这样写两三个数组,我的编译器就不运行了,改成宏定义就好了,不知道是不是适合其他编译器。
二、难题解决
描述
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.
输入
- 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
输出- Line 1: The maximum number of gallons of milk that Bessie can product in the N hours
样例输入
12 4 2
1 2 8
10 12 19
3 6 24
7 10 31
样例输出
43
错误思路:对第三个输入efficincyi理解有误,以为是时间x效率=产量。
正确思路:将结束时间升序排列,如果挤完奶休息完还没开始下一次,判断挤奶后与会多于原计划的产量,求出最大产量。
- Line 1: The maximum number of gallons of milk that Bessie can product in the N hours
#include<iostream>
#include<algorithm>
using namespace std;
struct num{
int sta,end,eff;
}cow[1010];
bool cmp(num x,num y)
{ return x.end<y.end;}
int main()
{ int n,m,r,i,j,dp[1010];
cin >> n>>m>>r;
for(i=0;i<m;i++)
{cin>>cow[i].sta>>cow[i].end>>cow[i].eff;}
sort(cow,cow+m,cmp);
for(i=0;i<m;i++)
{ dp[i]=cow[i].eff;}
int maxsum=0;
for(i=0;i<m;i++)
{ for(j=i+1;j<m;j++)
{ if(cow[i].end+r<=cow[j].sta)
{dp[j]=max(dp[j],dp[i]+cow[j].eff);}
}
maxsum=max(maxsum,dp[i]);
}
cout << maxsum << endl;
return 0;
}
动态规划的题目前,就这一个通过了,其他的还没完善,多多努力吧。
三、感悟
状态转移方程确定dp代表什么量,明白i-1,j-1是什么,理清dp之间的传递关系。
在代码算对的前提下再对代码进行删减来减小时间和空间复杂度。