一、题目描述
The Triangle
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 64432 Accepted: 38563
Description
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
(Figure 1)
Figure 1 shows a number triangle. Write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right.
Input
Your program is to read from standard input. The first line contains one integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100. The numbers in the triangle, all integers, are between 0 and 99.
Output
Your program is to write to standard output. The highest sum is written as an integer.
Sample Input
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
Sample Output
30
Source
IOI 1994
二、算法分析说明
设 t[i][j] 为三角形上第 i 行第 j 列的值,d[i][j] 为从 t[1][1] 开始不断往左下或右下走直到 t[i][j] 的过程中经过的全部数字的最大和。
易知递推边界:d[1][1] = t[1][1],d[i][1] = d[i - 1][1] + t[i][1],d[i][i] = d[i - 1][i - 1] + t[i][i]。
递推公式:d[i][j] = max(d[i - 1][j - 1], d[i - 1][j]) + t[i][j]
三、AC 代码(0 ms)
#include<cstdio>
#include<algorithm>
#pragma warning(disable:4996)
unsigned t[101][101], d[102][102], n;
int main() {
scanf("%u", &n);
for (unsigned i = 1; i <= n; ++i)
for (unsigned j = 1; j <= i; ++j)
scanf("%u", &t[i][j]);
d[1][1] = t[1][1];
for (unsigned i = 2; i <= n; ++i) {
d[i][1] = d[i - 1][1] + t[i][1]; d[i][i] = d[i - 1][i - 1] + t[i][i];
}
for (unsigned i = 3; i <= n; ++i)
for (unsigned j = 2; j < i; ++j)
d[i][j] = std::max(d[i - 1][j - 1], d[i - 1][j]) + t[i][j];
printf("%u\n", *std::max_element(&d[n][1], &d[n][n + 1]));
return 0;
}
该博客介绍了POJ 1163问题,即求解一个数字三角形中从顶部到底部的最大路径和。通过递推公式`d[i][j] = max(d[i - 1][j - 1], d[i - 1][j]) + t[i][j]`来找到最大路径,并给出了AC代码实现,运行时间为0 ms。"
113344996,10548130,64GB MySQL配置优化:16核系统提升性能,"['MySQL配置优化', '高性能数据库', '数据库管理', 'MySQL调优', '服务器配置']
268

被折叠的 条评论
为什么被折叠?



