题目描述 Description
有如图数塔,从顶部出发,在每一节点选择向左走或向右走,一直走到底。要求找到一个路径,使路径总和最大。
13
11 8
12 7 26
6 14 15 8
12 7 13 24 11
输入描述 Input Description
第一行输入一正整数n
接下来从第2行到第n+1行每行输入行数减1个正整数m。
输出描述 Output Description
共两行
第一行输出最大总和;
第二行输出最大路径,用‘-’隔开;
样例输入 Sample Input
5
13
11 8
12 7 26
6 14 15 8
12 7 13 24 11
样例输出 Sample Output
86
13-8-26-15-24
数据范围及提示 Data Size & Hint
40%数据:n<=20 , m<=1000
60%数据:n<=60 , m<=1050
代码:
#include<cstdio>
#include<algorithm>
using namespace std;
bool d;
int b[101][101],c[101][101],n,tot;
int main(){
int i,j;
scanf("%d",&n);
for(i=1;i<=n;i++){
for(j=1;j<=i;j++){
scanf("%d",&b[i][j]);
c[i][j]=b[i][j];
}
}
for(i=n-1;i>=1;i--)
for(j=1;j<=i;j++)
b[i][j]+=max(b[i+1][j],b[i+1][j+1]);
printf("%d
%d-",b[1][1],c[1][1]);
j=1;
for(int i=2;i<=n;i++){
if(b[i][j]>=b[i][j+1])
printf("%d",c[i][j]);
else{
printf("%d",c[i][j+1]);
j++;
}
if(i!=n)
printf("-");
}
return 0;
}