P1508
所属知识点:DP
主要题意:
就是求一个矩阵从下边走到上边,可以走自己前方或左前方或右前方.
问走到上边一共经过的路径和.
类型题:P1216
解题思路:
参考上边的类型题(因为比较简单),我们可以从上边开始反着走走到下边.
反着走的话,我们可以知道当前这个地方的权值是由下方,左下方,走下方走来的.
因为问的是吃的能量最多,我们就取在三个地方中取一个max然后再加上当前这个地方的权值.
用一个式子可以表示为. f[i][j] = max(f[i - 1][j] , f[i - 1][j - 1], f[i - 1][j + 1]) + a[i][j];
f[i][j] 表示吃到这个地方一共可以吃到的最大能量值,
a[i][j] 表示这个地方食物的能量值.
期待已久的code上场啦:
#include <iostream>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <algorithm>
#define A 210
using namespace std;
int n, m, map[A][A];
int ans;
int read() {
int s = 0, f = 0; char ch = getchar();
while (!isdigit(ch)) f |= (ch == '-'), ch = getchar();
while (isdigit(ch)) s = s * 10 + (ch ^ 48), ch = getchar();
return f ? -s : s;
}
int main(){
n = read(), m = read();
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
map[i][j] = read();
for(int i = 2; i <= n; i++){
for(int j = 1; j <= m; j++){
int a = max(map[i - 1][j - 1], map[i - 1][j]);
map[i][j] += max(a, map[i - 1][j + 1]);
}
}
ans = max(map[n][m / 2], map[n][m / 2 + 1]);
ans = max(ans, map[n][m / 2 + 2]);
cout<<ans;
}