寒假每日一题 898. 数字三角形(我爱喝水)

898. 数字三角形

AC1

# include <bits/stdc++.h>

using namespace std;

const int N = 510;
const int INF = 1E9+10;
int a[N], dp[N];

int main(){
    
    
    ios::sync_with_stdio(0);
    int n;
    cin>>n;
    for(int i = 0; i <= n; i ++ )dp[i] = -INF;
    dp[1] = 0;
    for(int i = 1; i <= n; i ++ ){
    
    
        for(int j = 1; j <= i; j ++ ) cin>>a[j];
        for(int j = i; j >= 1; j -- ) dp[j] = max(dp[j],dp[j-1])+a[j];
    }
    int res = -INF;
    for(int i = 1; i <= n; i ++ ) res = max(res,dp[i]);
    cout<<res<<endl;
    return 0;
}

AC2(从后往前dp)

# include <bits/stdc++.h>

using namespace std;

const int N = 510;

int dp[N][N];

int main(){
    
    
    ios::sync_with_stdio(0);
    int n; cin>>n;
    for(int i = 1; i <= n; i ++ ){
    
    
        for(int j = 1; j <= i; j ++ ) cin>>dp[i][j];
    }
    for(int i = n-1; i >= 1; i -- ){
    
    
        for(int j = 1; j <= i; j ++ ) dp[i][j] += max(dp[i+1][j],dp[i+1][j+1]);
    }
    cout<<dp[1][1]<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45377553/article/details/112436544