dp33分,求调

P1216 [USACO1.5] [IOI1994]数字三角形 Number Triangles

AcxxMz @ 2022-09-27 12:35:54

链接

#include<bits/stdc++.h>
using namespace std;
const int k=105;
int n,a[k][k],dp[k][k],maxi=-1e9;
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=i;j++)
            cin>>a[i][j];
    dp[1][1]=a[1][1];
    for(int i=1;i<=n;i++)
        for(int j=1;j<=i;j++)
        {
            if(i==j)
                dp[i][j]=dp[i-1][j]+a[i][j];
            else if(j==1)
                dp[i][j]=dp[i-1][j]+a[i][j];
            else
                dp[i][j]=max(dp[i-1][j-1],dp[i-1][j])+a[i][j];
        }
    for(int i=1;i<=n;i++)
        maxi=max(maxi,dp[n][i]);
    cout<<maxi;
    return 0;
}

by Foggy_night @ 2022-09-27 13:06:49


if(i==j)
    dp[i][j]=dp[i-1][j]+a[i][j];    
else if(j==1)
    dp[i][j]=dp[i-1][j]+a[i][j];

????


by Ayano_Kimishima @ 2022-10-06 08:55:58

无需判断。直接: dp[i][j]=max(dp[i-1][j-1],dp[i-1][j])+a[i][j]; 因为全局变量没输入的地方为0,不用判断边界。


by 吾爱Cpp @ 2022-10-20 15:54:47

两处问题,1,k应该大于1000

2,i==j时,应该是

dp[i][j] = dp[i - 1][j - 1] + a[i][j]

by lfy666_lifeiyang @ 2022-11-12 18:18:18


#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1001;
typedef long long ll;
ll n, a[N][N], dp[N][N];

/*
1、状态设计:
    dp[i][j]:从(1, 1) -> (i, j)的最大值
2、状态转移:
    dp[i][j] = max(dp[i + 1][j], dp[i][j + 1]) + a[i][j]; 
3、初始化:
    dp[n][i] = a[n][i];
4、递推顺序:
    自底向上      
5、输出:
    max(dp[n][1]~dp[n][n]) 
*/

//人人为我(自底向上) 
ll dp_function() { 
    cin >> n;
    for(ll i = 1; i <= n; i ++) 
        for(ll j = 1; j <= i; j ++)
            cin >> a[i][j];
    for(ll i = 1; i <= n; i ++)
        dp[n][i] = a[n][i];
    for(ll i = n - 1; i >= 1; i --) 
        for(ll j = 1; j <= i; j ++) 
            dp[i][j] = max(dp[i + 1][j], dp[i + 1][j + 1]) + a[i][j];
    return dp[1][1];
}

int main() {
    cout << dp_function() << endl;
    return 0;
}

/*
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5 

30
*/

|