1. 程式人生 > >POJ-2385 Apple Catching---DP

POJ-2385 Apple Catching---DP

net tor cin 一定的 class return cout 時間 bsp

題目鏈接:

https://vjudge.net/problem/POJ-2385

題目大意:

兩顆蘋果樹每一分會有樹落下蘋果,有人去接,但是來回兩個樹之間的次數是一定的,所以求出在最大次數時最多能接到多少蘋果。

思路:

dp[i][j]表示在時間i,已經來回了j次時的最大蘋果數目。

初始化dp[1][0]和dp[1][1]得根據第一個蘋果是哪棵樹落下的來進行初始化

轉移方程:dp[i][j] = max(dp[i-1][j], dp[i-1][j-1]),並且如果在這個狀態下,如果有蘋果下落,得自加一

根據j的奇偶來判斷在哪棵樹下面,j為奇數在tree-2下面,j為偶數在tree-1下面

 1 #include<iostream>
 2
#include<vector> 3 #include<queue> 4 #include<algorithm> 5 #include<cstring> 6 #include<cstdio> 7 #include<set> 8 #include<map> 9 #include<cmath> 10 #include<sstream> 11 using namespace std; 12 typedef pair<int, int> Pair; 13 typedef long
long ll; 14 const int INF = 0x3f3f3f3f; 15 int T, n, m, minans; 16 const int maxn = 1e3 + 10; 17 const int mod = 1e9; 18 int a[maxn]; 19 int dp[maxn][40];//dp[i][j]表示前i分鐘轉移j次的最大蘋果數目 20 int main() 21 { 22 cin >> n >> m; 23 for(int i = 1; i <= n; i++)cin >> a[i], a[i] %= 2; 24 if
(a[1] == 1)//初始狀態 25 { 26 dp[1][0] = 1; 27 dp[1][1] = 0; 28 } 29 else 30 { 31 dp[1][0] = 0; 32 dp[1][1] = 1; 33 } 34 for(int i = 2; i <= n; i++) 35 { 36 for(int j = 0; j <= m; j++) 37 { 38 if(j == 0) 39 //一次都沒有轉移,一直在tree1,如果此時a[i]為1,tree1掉蘋果,可以加上,反之加上的也是0 40 dp[i][j] = dp[i - 1][j] + a[i]; 41 else 42 { 43 dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1]); 44 45 //此時轉移j次 46 //j為奇數,在2下,若此時有蘋果,則加一 47 if((j % 2 == 1) && (a[i] == 0)) 48 dp[i][j]++; 49 //j為偶數,在1下,若此時有蘋果,則加一 50 if((j % 2 == 0) && (a[i] == 1)) 51 dp[i][j]++; 52 } 53 } 54 } 55 int ans = 0; 56 for(int i = 0; i <= m; i++)ans = max(ans, dp[n][i]); 57 cout<<ans<<endl; 58 return 0; 59 }

POJ-2385 Apple Catching---DP