poj 1163 The Triangle 동적 계획

4548 단어
귀속
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,d[124][124],ans[124][124];

int maxans(int i,int j)
{
    if(ans[i][j]!=-1)
        return ans[i][j];
    if(i==n) return d[i][j];
    int x=maxans(i+1,j);
    int y=maxans(i+1,j+1);
    ans[i][j]=max(x,y)+d[i][j];
    return ans[i][j];
}

int main()
{
    int i,j;
    while(~scanf("%d",&n))
    {
        memset(d,0,sizeof(d));
        for(i=1;i<=n;i++)
            for(j=1;j<=i;j++)
        {
            scanf("%d",&d[i][j]);
            ans[i][j]=-1;
        }
        maxans(1,1);
        printf("%d
"
,ans[1][1]); } return 0; }

점차 미루다
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,d[124][124],ans[124][124];

int main()
{
    int i,j;
    while(~scanf("%d",&n))
    {
        memset(d,0,sizeof(d));
        memset(ans,0,sizeof(ans));
        for(i=1;i<=n;i++)
            for(j=1;j<=i;j++)
                scanf("%d",&d[i][j]);
        for(j=1;j<=n;j++) ans[n][j]=d[n][j];
        for(i=n-1;i>=1;i--)
        {
            for(j=1;j<=i;j++)
            {
                ans[i][j]=max(ans[i+1][j],ans[i+1][j+1])+d[i][j];
            }
        }
        printf("%d
"
,ans[1][1]); } return 0; }

좋은 웹페이지 즐겨찾기