POJ1163 The Triangle

来源:互联网 发布:新闻资讯源码 作家 编辑:程序博客网 时间:2024/06/09 16:37

The Triangle

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 45876 Accepted: 27745

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


题目意思:像图一所示的数字三角形,编写程序计算从顶到底的路径的最大值是多少。每一步只能从当前位置到当前位置左下角或右下角的数。

<span style="font-size:14px;">#include <stdio.h>#include <string.h>int main(){    int cur[100][100],num,maxnum=0;//maxnum保存当前的最大值    memset(cur,0,sizeof(cur));    scanf("%d",&num);    for(int i = 0; i<num; i++)    {        for(int j=0; j<=i; j++)        {            scanf("%d",&cur[i][j]);            if(!j&&i) cur[i][j]=cur[i-1][j]+cur[i][j];//如果当前数是在最左侧,那么从右上角的数到达它            if(j&&i)  cur[i][j]=(cur[i-1][j]>cur[i-1][j-1]?cur[i-1][j]:cur[i-1][j-1])+cur[i][j];//否则比较左上角和右上角的数,选择较大的数作为它上一步的数            maxnum=maxnum>cur[i][j]?maxnum:cur[i][j];//更新最大数        }    }    printf("%d\n",maxnum);}</span>


如图所示,在每次读入数据之后,该位置将结合上层的结果更新该位置的值,更新方法是对比左上角和右上角值的大小,将更大者与自已相加,并保存相加的值。而动态规划的思想是将待求解问题分解成若干个子问题,先求解子问题,然后从这些子问题的解得到原问题的解。

动态规划的基本模型如下:
(1)确定问题的决策对象。 (2)对决策过程划分阶段。 (3)对各阶段确定状态变量。 (4)根据状态变量确定费用函数和目标函数。 (5)建立各阶段状态变量的转移过程,确定状态转移方程。

在该问题中,决策的对象是上一层中当前结点的左上方和右上方对应的值,每一层对应一个阶段,当前阶段状态变量是当前阶段每个结点的值,根据每个的结点的值和左右上方的值的和更新当前结点的值



0 0
原创粉丝点击