[Dynamic Programming] triangular numbers

Original title Portal

Thinking


This question is on the label is CODEVS dynamic programming, but this Tacca wanted for a long time thought out (probably I was too weak ......), he intended to write a revealing look at the search can be mixed with a bit , then 20 minutes of time code complete DFS, pay up, AC? ? ! This question data words so not to force it? ? ? Data also so small that with what DP ah ???Waste hairlineHowever, dynamic programming is definitely faster than the burst search, if the data is large enough, burst search is not AC, but after all, the intention of solving the problem of dynamic programming is to practice, so I thought the idea of ​​dynamic programming, the final dynamic programming code is also made out, AC ~~~

DFS-Code


#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<stack>
#include<map>
using namespace std;

int i,j,n,MAX=-99999999,a[101][101]; 

void dfs(int x,int y,int v)
{
    int newvalue=v+a[x][y];
    if(x==n)
    {
        if(newvalue>MAX)
            MAX=newvalue;
        return;
    }
    dfs(x+1,y,newvalue);
    dfs(x+1,y+1,newvalue);
}

int main()
{
    cin>>n;
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=i;j++)
        {
            cin>>a[i][j];
        }
    }
    dfs(1,1,0);
    cout<<MAX;
    return 0;
}

DP-Code


#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<stack>
#include<map>
using namespace std;

int i,j,n,MAX=-99999999,a[101][101],dp[101][101]; 



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

Guess you like

Origin www.cnblogs.com/gongdakai/p/11402482.html