poj 1163 The Triangle 动态规划
递归
#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\n",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\n",ans[1][1]);
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。http://xiang578.top/