Filthy Rich 题解

They say that in Phrygia, the streets are paved with gold. You’re currently on vacation in Phrygia, and to your astonishment you discover that this is to be taken literally: small heaps of gold are distributed throughout the city. On a certain day, the Phrygians even allow all the tourists to collect as much gold as they can in a limited rectangular area. As it happens, this day is tomorrow, and you decide to become filthy rich on this day. All the other tourists decided the same however, so it’s going to get crowded. Thus, you only have one chance to cross the field. What is the best way to do so? 

Given a rectangular map and amounts of gold on every field, determine the maximum amount of gold you can collect when starting in the upper left corner of the map and moving to the adjacent field in the east, south, or south-east in each step, until you end up in the lower right corner. 

Input

The input starts with a line containing a single integer, the number of test cases. 
Each test case starts with a line, containing the two integers r and c, separated by a space (1 <= r, c <= 1000). This line is followed by r rows, each containing c many integers, separated by a space. These integers tell you how much gold is on each field. The amount of gold never negative. 
The maximum amount of gold will always fit in an int.

Output

For each test case, write a line containing “Scenario #i:”, where i is the number of the test case, followed by a line containing the maximum amount of gold you can collect in this test case. Finish each test case with an empty line. 

Sample Input

1
3 4
1 10 8 8
0 0 1 8
0 27 0 4

Sample Output

Scenario #1:
42

题解:给了一个长为n,宽了m的矩阵,矩阵的每个位置都有一个数字,每次只能往下,往右走,并能得到这个点的数字,问怎样才能从左上到右下得da到得数字之和最大。

思路:上来一看时间,想都没想就写了一个搜索,一交就TL,后来一看原来是简单得dp题,因为每次只能往两个方向走,所以最上面得那一行只能是一直往右走得到得,同理,最左面的那一列肯定是一直向下得到的。对于中间的点来说就有从上面下来,或者从左面过来两种方式到达,因此每次取到达这个点最大的方式,一直往下找,最后输出右下角的点的dp值。

代码如下:

#include<cstdio>
#include<cstring>
int dp[1010][1010];
int main()
{
    int t,n,m,i,j,k=1;
    scanf("%d",&t);
    while(t--)
    {
        int x;
        scanf("%d%d",&n,&m);
        memset(dp,0,sizeof(dp)); //初始化
        scanf("%d",&dp[0][0]);   //左上角
        for(i=1;i<m;i++)
        {
            scanf("%d",&x);     //输入第一行,这点的最大值是有右边那个数加x得到
            dp[0][i]=dp[0][i-1]+x;
        }
        for(i=1;i<n;i++)
        {
            scanf("%d",&x);   //第一列的每一个值
            dp[i][0]=dp[i-1][0]+x; //最大值为上面那个数加x得到
            for(j=1;j<m;j++)
            {
                scanf("%d",&x);
                if(dp[i-1][j]>dp[i][j-1])  //上面那个数的最大值大于左面的话,取上面的值
                    dp[i][j]=dp[i-1][j]+x;
                else
                    dp[i][j]=dp[i][j-1]+x;  //取左面的值
            }
        }
        printf("Scenario #%d:\n%d\n\n",k++,dp[n-1][m-1]);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41890797/article/details/81104351