poj 3616 Milking Time (dp)
题意:选出工作的时间段,使产量最大,工作一个段后牛还要休息一个特定时间段,所以不能都选。
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
自己先写了顺着的状态方程,代码写的时候逆序求的,就是直接递推,没有递归正序写。
a[ i ]:从第 i 个出发可以得到的max
for(j=i+1 ; j<n&&p[ i ].y+r>p[ j ].x ; j++);
a[ i ]=max(a[ i+1 ] , p[ i ].w+a[ j ]);
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <cmath> 5 #include <algorithm> 6 using namespace std; 7 typedef struct 8 { 9 int x,y,w; 10 } P; 11 bool cmp(P p1,P p2) 12 { 13 if(p1.x<p2.x) return true; 14 else if(p1.x==p2.x) 15 { 16 if(p1.y<p2.y) return true; 17 else if(p1.y==p2.y) 18 { 19 if(p1.w<p2.w) return true; 20 } 21 } 22 return false; 23 } 24 int main() 25 { 26 int i,j; 27 int n,m,r; 28 scanf("%d%d%d",&n,&m,&r); 29 P p[m]; 30 for(i=0; i<m; i++) 31 { 32 scanf("%d%d%d",&p[i].x,&p[i].y,&p[i].w); 33 } 34 sort(p,p+m,cmp);//开始写成p+n了 35 36 int a[m+1]; 37 a[m]=0,a[m-1]=p[m-1].w; 38 for(i=m; i>=1; i--)//算a[i-1] 39 { 40 for(j=i; j<m&&p[i-1].y+r>p[j].x; j++);//找如果选i的话,满足休息后可以选的下一个记为j 41 if(j>m)j=m;//没有可以选的 42 a[i-1]=max(a[i],p[i-1].w+a[j]); 43 } 44 printf("%d\n",a[0]); 45 return 0; 46 }

浙公网安备 33010602011771号