就是求一个矩阵从下边走到上边,能够走本身前方或左前方或右前方.
问走到上边一共通过的路径和.ios
类型题:P1216git
参考上边的类型题(由于比较简单),咱们能够从上边开始反着走走到下边.spa
反着走的话,咱们能够知道当前这个地方的权值是由下方,左下方,走下方走来的.code
由于问的是吃的能量最多,咱们就取在三个地方中取一个max而后再加上当前这个地方的权值.get
用一个式子能够表示为. f[i][j] = max(f[i - 1][j] , f[i - 1][j - 1], f[i - 1][j + 1]) + a[i][j];string
f[i][j] 表示吃到这个地方一共能够吃到的最大能量值,it
a[i][j] 表示这个地方食物的能量值.io
#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; }