1. 程式人生 > >動態規劃 DP

動態規劃 DP

code tchar getch spa div 發現 style logs print

動態規劃 DP
我們用f[ i ] 表示從 i 點出發到達終點的最多能休息的時間

然後我們發現 狀態轉移方程
f[ i ] = f[ i+1 ] +1 ; 當該點 並沒有工作計劃時
f[ i ] = max(f[ i+len ],f[ i ]); 當該點 有工作計劃時 一個或若幹個

 1 #include <bits/stdc++.h> 
 2 #define For(i,j,k) for(int i=j;i<=k;i++) 
 3 using namespace std ; 
 4 
 5 const int N = 10011 ; 
 6
int n,k,p,len; 7 int f[N] ; 8 vector <int> v[N] ; 9 vector <int> :: iterator it ; 10 11 inline int read() 12 { 13 int x = 0 , f = 1 ; 14 char ch = getchar() ; 15 while(ch<0||ch>9) { if(ch==-) f = -1 ; ch = getchar() ; } 16 while(ch>=0&&ch<=
9) { x = x * 10+ch-48 ; ch = getchar() ; } 17 return x * f ; 18 } 19 20 int main() 21 { 22 n = read() ; k = read() ; 23 For(i,1,k) { 24 p = read() ; len = read() ; 25 v[ p ].push_back( len ) ; 26 } 27 f[ n+1 ] = 0 ; 28 for(int i=n;i>=1;i--) { 29
if( v[ i ].empty() ) 30 f[ i ] = f[ i+1 ] + 1 ; 31 else 32 for(it=v[ i ].begin();it!=v[ i ].end();it++) { 33 len = *it ; 34 f[ i ] = max( f[ i ],f[ i+len ] ) ; 35 } 36 } 37 printf("%d\n",f[ 1 ]) ; 38 return 0 ; 39 }

動態規劃 DP