1. 程式人生 > >【TOJ 3242】FatMouse and Java Beans(dp)

【TOJ 3242】FatMouse and Java Beans(dp)

ati sin row med AC inpu box his align

描述

FatMouse is lucky enough for it found a rectangular box in a storehouse which contains his favorite food-JavaBeans.
The box is splited into r*c cells, and in each cell there are some JavaBeans in it.
The problem is to determine the maximum amount of JavaBeans that FatMouse can collect when starting in the upper left corner of the box
and moving to the adjacent field in the east, south, or south-east in each step, until it end up in the lower right corner.

輸入

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).
Then followed by r rows, each containing c integers, separated by a space. These
integers show how many JavaBeans are there in each cell. The amount of JavaBeans never negative.
The maximum amount of JavaBeans will always fit in an int.

輸出

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 JavaBeans that FatMouse can collect in this test case.
Finish each test case with an empty line.

樣例輸入

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

樣例輸出

Scenario #1:
42

題意

就是一個往二維數組右下角dp的辣雞題!只能往右和往下走,每次路徑的值都可以相加,求最大值。

#include <bits/stdc++.h>
using namespace std;
int a[1005][1005];
int main()
{
    int n,m,i,j,t,num=0;
    cin>>t;
    while(t--)
    {
        num++;
        cin>>n>>m;
        for(i=1;i<=n;i++)
            for(j=1;j<=m;j++) 
                scanf("%d",&a[i][j]);
                
        for(i=1;i<=m;i++) 
            a[1][i]=a[1][i]+a[1][i-1];
        for(i=1;i<=n;i++)
            a[i][1]=a[i][1]+a[i-1][1];
            
        for(i=2;i<=n;i++)
            for(j=2;j<=m;j++)
                a[i][j]=max(a[i][j-1],a[i-1][j])+a[i][j];

        cout<<"Scenario #"<<num<<":"<<endl;
        cout<<a[n][m]<<endl<<endl;
    }
}

【TOJ 3242】FatMouse and Java Beans(dp)