poj 2385 Apple Catching

來源:互聯網
上載者:User

標籤:

題目大意:有兩棵蘋果樹,編號為1,2,每分鐘有一棵樹會掉落一個蘋果。一頭牛在樹下接蘋果,每分鐘只能站在一棵樹下,但在樹間轉移的時間忽略不計。給定最大的轉移次數w,問這隻牛最多能接住多少蘋果?

分析:這道題用動態規劃求解,關鍵問題是狀態是什嗎?

    不妨按時間來思考,一給定時刻i,轉移次數已知為j, 則它只能由兩個狀態轉移而來。

    即上一時刻同一棵樹或上一時刻不同的樹

    則這一時刻在轉移次數為j的情況下最多能接到的蘋果為那兩個狀態的最大值再加上當前能接受到的蘋果。(注意當前能否拿到蘋果只與轉移次數有關)

   即

1 dp[i][j] = max(dp[i-1][j], dp[i-1][j-1]);2 if(j%2+1 == i) {3     dp[i][j]++;4 }

在0時刻,不管移動次數為幾,接受的蘋果都為0

本題代碼如下

  

 1 /*dp[t][w] 2  3 dp[0][0..w] = 0; 4 dp[i][0] = dp[i-1][0]; 5 dp[i][j] = max(dp[i-1][j], dp[i-1][j-1]); 6 if(j%2+1 == i) { 7     dp[i][j]++; 8 }*/ 9 #include <cstdio>10 #include <cstring>11 #include <iostream>12 using namespace std;13 int dp[1002][35];14 int apple[1002];15 16 int main(int argc, char const *argv[])17 {18     int t, w;19     scanf("%d %d",&t,&w);20         for(int i = 1; i <= t; i++) {21             scanf("%d",&apple[i]);22         }23         memset(dp, 0, sizeof(dp));24         for(int i = 1; i <= t; i++) {25             for(int j = 0; j <= w; j++) {26                 if(j == 0) {27                     dp[i][j] = dp[i-1][j];28                 }29                 else {30                     dp[i][j] = max(dp[i-1][j], dp[i-1][j-1]);31                 }32                 if(j%2 + 1 == apple[i]) {33                     dp[i][j]++;34                 }35             }36         }37         int ans = dp[t][0];38         for(int j = 1; j <= w; j++) {39             if(ans < dp[t][j]) {40                 ans = dp[t][j];41             }42         }43         printf("%d\n",ans);44 45     46     return 0;47 }

動態規劃確實不容易啊!

poj 2385 Apple Catching

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.