目录
牛客_DP39字母收集_路径DP
题目解析
- 首先定义一个二维dp数组,dp[i][j]表示走到i行j列的时候,小红最多能获取多少分。
- 然后确定状态如何转化。每一步中,小红要么从左边格子到当前位置,要么从上边格子到当前位置,两者取较大的一个,所以dp[i][j]=Math.max(dp[i−1][j],dp[i][j−1])+getScore(arr[i][j])dp[i][j]=Math.max(dp[i−1][j],dp[i][j−1])+getScore(arr[i][j])。
C++代码
#include <iostream>
using namespace std;
const int N = 510;
char g[N][N];
int dp[N][N];
int m, n;
int main()
{
cin >> m >> n;
for(int i = 1; i <= m; i++)
{
for(int j = 1; j <= n; j++)
{
cin >> g[i][j];
}
}
for(int i = 1; i <= m; i++)
{
for(int j = 1; j <= n; j++)
{
int t = 0;
if(g[i][j] == 'l')
t = 4;
else if(g[i][j] == 'o')
t = 3;
else if(g[i][j] == 'v')
t = 2;
else if(g[i][j] == 'e')
t = 1;
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) + t;
}
}
cout << dp[m][n] << endl;
return 0;
}
Java代码
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt(), m = in.nextInt();
char[][] arr = new char[n + 1][m + 1];
for(int i = 1; i <= n; i++)
{
char[] s = in.next().toCharArray();
for(int j = 1; j <= m; j++)
{
arr[i][j] = s[j - 1];
}
}
int[][] dp = new int[n + 1][m + 1];
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
int t = 0;
if(arr[i][j] == 'l')
t = 4;
else if(arr[i][j] == 'o')
t = 3;
else if(arr[i][j] == 'v')
t = 2;
else if(arr[i][j] == 'e')
t = 1;
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]) + t;
}
}
System.out.println(dp[n][m]);
}
}