数字塔问题。给定一个具有N层的数字三角形,从顶至底有多条路径,每一步可沿左斜线向下或沿右斜线向下,路径所经过的数字之和为路径得分,请求出最大路径得分。
#include<stdio.h>
int max(int x,int y);
int main()
{
int i,j;
int a[5][5]={
{7,0,0,0,0},
{3,8,0,0,0},
{8,1,0,0,0},
{2,7,4,4,0},
{4,5,2,6,5}};
int b[5][5];
for(i=0;i<5;i++){
for(j=0;j<5;j++) b[i][j]=a[i][j];
}
for(i=3;i>=0;i--){
for(j=0;j<5;j++)
a[i][j]=a[i][j]+max(a[i+1][j],a[i+1][j+1]);
}
for(i=0;i<5;i++){
for(j=0;j<5;j++) printf("%5d ",a[i][j]);
putchar('\n');
}
int temp=0;
temp=a[0][0]-b[0][0];
printf("The path is :");
printf("-->(%d,%d)",0,0);
for(i=1;i<5;i++){
for(j=0;j<5;j++){
if(temp==a[i][j]){
temp=a[i][j]-b[i][j];
printf("-->(%d,%d)",i,j);
break;
}
else continue;
}
}
return 0;
}
int max(int x,int y)
{
return x>y?x:y;
}
程序运行结果演示