题目:
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
大意:
首先输入一个正整数,代表测试数据的组数
每组数据第一行由两个数r和c组成(分别代表行数和列数)
接着有r行,每行有c列数
问从左上走到右下所经过的数字之和最大(只能向右、向左、向右下走)
思路:
运用dp的思想,写出动态转移方程dp[i][j]=max(dp[i-1][j],max(dp[i][j-1],dp[i-1][j-1]))+mp[i][j];
所以到右下所经过的最大数字之和就等于dp[r][c];
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a,b,mp[1010][1010];
int dp[1010][1010];
int main()
{
int n,k=1;
scanf("%d",&n);
while(n--)
{
memset(dp,0,sizeof(dp));
scanf("%d%d",&a,&b);
for(int i=1;i<=a;i++)
{
for(int j=1;j<=b;j++)
{
scanf("%d",&mp[i][j]);
}
}
for(int i=1;i<=a;i++)
{
for(int j=1;j<=b;j++)
{
dp[i][j]=max(dp[i-1][j],max(dp[i][j-1],dp[i-1][j-1]))+mp[i][j];
}
}
printf("Scenario #%d:\n",k++);
printf("%d\n\n",dp[a][b]);
}
return 0;
}