(hdu)5234 Happy birthday 二维dp+01背包

时间:2023-03-08 20:56:48
(hdu)5234  Happy birthday    二维dp+01背包

题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=5234

Problem Description
Today is Gorwin’s birthday. So her mother want to realize her a wish. Gorwin says that she wants to eat many cakes. Thus, her mother takes her to a cake garden. The garden is splited into n*m grids. In each grids, there is a cake. The weight of cake in the i-th row j-th column is wij kilos, Gorwin starts from the top-left(,) grid of the garden and walk to the bottom-right(n,m) grid. In each step Gorwin can go to right or down, i.e when Gorwin stands in (i,j), then she can go to (i+,j) or (i,j+) (However, she can not go out of the garden). When Gorwin reachs a grid, she can eat up the cake in that grid or just leave it alone. However she can’t eat part of the cake. But Gorwin’s belly is not very large, so she can eat at most K kilos cake. Now, Gorwin has stood in the top-left grid and look at the map of the garden, she want to find a route which can lead her to eat most cake. But the map is so complicated. So she wants you to help her. Input
Multiple test cases (about ), every case gives n, m, K in a single line. In the next n lines, the i-th line contains m integers wi1,wi2,wi3,⋯wim which describes the weight of cakes in the i-th row Please process to the end of file. [Technical Specification] All inputs are integers. <=n,m,K<= <=wij<= Output
For each case, output an integer in an single line indicates the maximum weight of cake Gorwin can eat. Sample Input Sample Output Hint
In the first case, Gorwin can’t eat part of cake, so she can’t eat any cake. In the second case, Gorwin walks though below route (,)->(,)->(,)->(,). When she passes a grid, she eats up the cake in that grid. Thus the total amount cake she eats is +++=.

题意:一个N*M的方阵,每个值代表蛋糕量,只能选择吃完或不吃,从(1,1)只能向下和向右走的情况下到(n,m)。问在不超过K值情况下,最多能吃多少?

方法:用dp[i][j][k]表示在(i,j)点不超过k的情况下能吃多少

#include<cstdio>
#include<cstring>
#include<queue>
#include<cstdlib>
#include<algorithm>
#include<iostream>
using namespace std;
#define ll long long
#define met(a,b) memset(a,b,sizeof(a));
const int oo = 0x3f3f3f3f;
const int N = ;
int a[N][N],dp[N][N][N];
int main()
{
int n,m,k;
while(scanf("%d %d %d",&n,&m,&k)!=EOF)
{
for(int i=;i<=n;i++)
{
for(int j=;j<=m;j++)
scanf("%d",&a[i][j]);
}
met(dp,);
for(int i=;i<=n;i++)
{
for(int j=;j<=m;j++)
{
for(int l=k;l>=a[i][j];l--)
{
int x=max(dp[i-][j][l],dp[i][j-][l]);///表示i,j这个点如果不拿能拿到的最大值
int y=max(dp[i-][j][l-a[i][j]]+a[i][j],dp[i][j-][l-a[i][j]]+a[i][j]);
///如果在不超过k的情况下拿i,j这个点所能拿的最大值
dp[i][j][l]=max(x,y);
}
}
}
printf("%d\n",dp[n][m][k]);
}
return ;
}