参考代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int data[105][105];int main()
{ios::sync_with_stdio(false);int n;cin >> n;for(int i = 1; i <= n; i++){for(int j = 1; j <= i; j++){cin >> data[i][j];}}int dp[105][105], cnt[105][105] = {0};dp[1][1] = data[1][1];for(int i = 2; i <= n; i++){dp[i][1] = dp[i-1][1] + data[i][1];cnt[i][1] = cnt[i-1][1] - 1;for(int j = 2; j <= i-1; j++){if(dp[i-1][j-1] > dp[i-1][j]){dp[i][j] = dp[i-1][j-1] + data[i][j];cnt[i][j] = cnt[i-1][j-1] + 1;}else{dp[i][j] = dp[i-1][j] + data[i][j];cnt[i][j] = cnt[i-1][j] - 1;}}dp[i][i] = dp[i-1][i-1] + data[i][i];cnt[i][i] = cnt[i-1][i-1] + 1;}int maxn = 0;for(int i = 1; i <= n; i++){if(dp[n][i] > maxn && cnt[n][i] <= 1 && cnt[n][i] >= -1)maxn = dp[n][i];}cout << maxn;return 0;
}