HDU 5234 Happy birthday --- 三維01背包

來源:互聯網
上載者:User

標籤:

 

  HDU 5234

  題目大意:給定n,m,k,以及n*m(n行m列)個數,k為背包容量,從(1,1)開始只能往下走或往右走,求到達(m,n)時能獲得的最大價值

  解題思路:dp[i][j][k]表示在位置(i,j)有一個容量為k的背包所能獲得的最大價值

       決策:a[i][j]處的數是否選取

       不選取: dp[i][j][k]= max(dp[i-1][j][k], dp[i][j-1][k])

       選取:首先要求k >=a[i][j],那麼dp[i][j][k] = max(dp[i-1][j][k-w[i][j]], dp[i][j-1][k-w[i][j]]);

       相當於求四者的最大值,最後dp[m][n][k]即為所求結果

/* HDU 5234 Happy birthday --- 三維01背包 */#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int maxn = 105;int w[maxn][maxn];int dp[maxn][maxn][maxn];int n, m, V;int main(){#ifdef _LOCAL    freopen("D:\\input.txt", "r", stdin);#endif    //n行m列容量為V    while (scanf("%d%d%d", &n, &m, &V) == 3){        for (int i = 1; i <= n; ++i){            for (int j = 1; j <= m; ++j){                scanf("%d", w[i] + j);            }//for(j)        }//for(i)        memset(dp, 0, sizeof dp);        for (int i = 1; i <= n; ++i){            for (int j = 1; j <= m; ++j){                for (int k = 0; k <= V; ++k){                    //w[i][j]不取的時候                    int a = max(dp[i - 1][j][k], dp[i][j - 1][k]);                    int b = 0;                    //k > w[i][j], w[i][j]取的時候                    if (k - w[i][j] >= 0){                        b = max(dp[i - 1][j][k - w[i][j]], dp[i][j - 1][k - w[i][j]]) + w[i][j];                    }                    dp[i][j][k] = max(a, b);                }            }//for(j)        }//for(i)        printf("%d\n", dp[n][m][V]);    }    return 0;}
View Code

 

HDU 5234 Happy birthday --- 三維01背包

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.