用的y总的dp分析法,题解已发布到acwing上,在CSDN记录一下
三维dp:
![](https://img-blog.csdnimg.cn/direct/c27b51c88b504b37aa67a8596fa67a0c.png)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 110;
int num[N][N], dp[N][N][N];
int main(){
int n;
cin >> n;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= i; j++){
cin >> num[i][j];
}
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= i; j++){
for(int k = 0; k <= i - 1; k++){
dp[i][j][k] = dp[i - 1][j][k] + num[i][j];
if(k >= 1){
dp[i][j][k] = max(dp[i - 1][j][k], dp[i - 1][j - 1][k - 1]) + num[i][j];
}
}
}
}
int res = 0;
if(n % 2 == 0){//此时 k = n - 1是奇数会有两种答案
//向右走(n - 1) / 2步或者向右走(n - 1) / 2 + 1步数
for(int i = 1; i <= n; i++){
res = max(res, dp[n][i][(n - 1) / 2]);
}
for(int i = 1; i <= n; i++){
res = max(res, dp[n][i][(n - 1) / 2 + 1]);
}
}
else{//此时 k = n - 1是偶数数只有一种答案
//向右走(n - 1) / 2步
for(int i = 1; i <= n; i++){
res = max(res, dp[n][i][(n - 1) / 2]);
}
}
cout << res << endl;
return 0;
}
二维dp:
![](https://img-blog.csdnimg.cn/direct/1d3051c86a2240e2a6641fde6f7d4462.png)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 110;
int num[N][N], dp[N][N];
int main(){
int n;
cin >> n;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= i; j++){
cin >> num[i][j];
}
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= i; j++){
if(dp[i - 1][j] >= dp[i - 1][j - 1]){
dp[i][j] = dp[i - 1][j] + num[i][j];//选下边,相当于三角形下一层左边
}
else{
dp[i][j] = dp[i - 1][j - 1] + num[i][j];//选右下边,相当于三角形下一层右边
}
}
}
int k = n / 2;
int p = k + 1;
if(n % 2 == 0){
cout << max(dp[n][k], dp[n][p]) << endl;
}
else{
cout << dp[n][p] << endl;
}
return 0;
}
dfs:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 110;
int num[N][N], n, res;
void dfs(int x, int y, int z, int s){//x,y表示当前坐标;z表示当前位移量,向右为正,向左为负;s表示当前总和
if(x == n){
if(z == 0 || z == 1 || z == -1){
res = max(res, s);
}
cout << res << endl;
return;
}
dfs(x + 1, y, z - 1, s + num[x + 1][y]);//向下走,相当于三角形中向左走
dfs(x + 1, y + 1, z + 1, s + num[x + 1][y + 1]);//向右下走,相当于三角形中向右走
}
int main(){
cin >> n;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= i; j++){
cin >> num[i][j];
}
}
dfs(1, 1, 0, num[1][1]);
cout << res << endl;
return 0;
}