您的位置:首页 > 其它

SCU 1114 数字三角

2016-07-29 15:46 302 查看
题目:
Description
下图是个数字三角,请编写一个程序计算从顶部至底部某处一条路径,使得该路径所经过的数字总和最大。73  88  1  02  7  4  41.  每一步可沿左斜线向下或右斜线向下走;2.  1<=三角形行数<=1003.  三角形中的数字为整数 0,1,……,99。4.  如果有多种情况结果都最大,任意输出一种即可。 输入:第一行一个整数N,代表三角形的行数。接下来N行,描述了一个数字三角。 输出:    第一行一个整数,代表路径所经过底数字总和。    第二行N个数,代表所经过的数字。 样例:输入:4 
7
3 8
8 1 0
2 7 4 4输出:25 
7 3 8 7
代码:
#include<iostream>
#include<string.h>
#include<stack>
using namespace std;

int main()
{
int n;
cin >> n;
int list[101][101];
memset(list, 0, sizeof(list));
cin >> list[1][1];
for (int i = 2; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
cin >> list[i][j];
list[i][j] += (list[i - 1][j] > list[i - 1][j - 1]) ? list[i - 1][j] : list[i - 1][j - 1];
}
}
int max = 0, key = 0;
for (int j = 1; j <= n; j++)
{
if (max < list[n][j])
{
max = list[n][j];
key = j;
}
}
cout << max << endl;
stack<int>s;
for (int i = n; i>0; i--)
{
if (list[i - 1][key] > list[i - 1][key - 1])
s.push(list[i][key] - list[i - 1][key]);
else s.push(list[i][key] - list[i-1][(key--)-1]);
}
while (!s.empty())
{
cout << s.top()<<" ";
s.pop();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: