- 1000ms
- 262144K
You are writing an app for your friend’s new Phone, the newPhone. Since you grew up on Pac Man, you want to write a simplified version of the game. In this game, the board is a rectangular grid and Pac Man starts at the upper left-hand corner. His goal is to get to the lower right-hand corner. He always moves one square to the right or one square down. Each square he goes to has a “goody” that’s worth a particular amount of points. Your score is simply the sum of the scores of the goodies in each square you have visited.
For example, if the game board looks like this (P indicates Pac Man’s starting location, and E indicates his ending location):
then Pac Man’s optimal strategy would be to move right, down, right, right again, then down to yield a score of 3 + 4 + 9 + 3 = 19.
The Problem:
Given a game board, determine the maximum possible score for Pac Man.
The Input:
There will be multiple game boards in the input file. The first input line contains a positive integer n, indicating the number of game boards to be processed. The first line of each game board will contain two positive integers, r (0 < r < 100) and c (1 < c < 100), representing the number of rows and columns for this game board. (The example above has three rows and four columns.) Each of the following r input lines will contain c tokens, representing the contents of that row. The first item on the first of these lines will be the character ‘P’, representing Pac Man’s original location and the last item on the last line will be the character ‘E’, representing Pac Man’s goal location. The rest of the items will be positive integers less than 1000. Items will be separated by a single space on each line.
The Output:
At the beginning of each test case, output “Game Board #g:”, where g is the input board number (starting from 1). For each game board, simply print out the maximum possible score for the game.
Leave a blank line after the output for each test case. Follow the format illustrated in Sample Output.
样例输入复制
2 3 4 P 3 2 8 1 4 9 3 6 2 2 E 2 2 P 5 401 E
样例输出复制
Game Board #1: 19 Game Board #2: 401
题解:
一开始使用递归+记忆化搜索来做的,结果TL了。
后来发现dp这么简单。因为只有向右、向下的操作,所以思路也比较简单。
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int g[110][110],dp[110][110];//dp存起始点到达dp[i][j]的最大值
int main()
{
int t;
cin>>t;
int num=0;
while(t--){
memset(g,0,sizeof g);
memset(dp,0,sizeof dp);
num++;
printf("Game Board #%d: ",num);
int row,col;
cin>>row>>col;
char c;
for(int i=1;i<=row;i++)
for(int j=1;j<=col;j++)
{
if(i==1&&j==1||i==row&&j==col) cin>>c;
else cin>>g[i][j];
}
for(int i=1;i<=row;i++)
for(int j=1;j<=col;j++) dp[i][j]=max(dp[i-1][j],dp[i][j-1])+g[i][j];//每次看一下,左边的大还是右边的大,选大的那个
cout<<dp[row][col]<<endl<<endl;
}
return 0;
}