经典动态规划问题--数字三角形 POJ--1163

来源:互联网 发布:程序员修炼之道pdf 编辑:程序博客网 时间:2024/05/19 20:56

The Triangle

Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 35683 Accepted: 21357

Description

73   88   1   02   7   4   44   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

573 88 1 0 2 7 4 44 5 2 6 5

Sample Output

30

解题思路:这道题目是动态规划的典型。其实递归,动态规划,分治从某种角度讲是十分的相近的。这个问题的子问题很明显是每次选择数字后对下一层的选择,每次都有两种。很容易想到用递归遍历每种解法,找到最大值。这种思路的好处是从上往下推,考虑比较正面。往往我们为了不超时间会开辟一个数组来存储我们已经计算得到的结果。也就是平常说的以空间换时间。

下面是递归的写法:

// 数字三角形问题.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include<iostream>#include<memory.h>#include<stdlib.h>#include<stdio.h>using namespace std;int a[110][110]={0};int record[110][110]={0};int n=0;int max_sum(int i,int j);int main(){while(scanf("%d",&n)!=EOF){memset(record,-1,sizeof(record));for(int i=0;i<n;i++)for(int j=0;j<=i;j++)    scanf("%d",&a[i][j]);int sum=max_sum(0,0);printf("%d",sum);}return 0;}int max_sum(int i,int j){if(i==n-1)return a[i][j];int left=0,right=0;if(record[i][j]==-1){left=a[i][j]+max_sum(i+1,j);right=a[i][j]+max_sum(i+1,j+1);record[i][j]=left>right?left:right;}return record[i][j];}


还有一种思考方式是从下往上推,具体来说就是假设轮到第i层的数字挑选他会从两个数字中和目前累计和最大的。

看下面这个例子,总共5层,

从第4层看。2会挑选5得到累加和7;7会挑选5得到累加和12;4会挑选6得到累加和10;下一个4会挑选6也得到10;

再看第3层。8会挑选累加和较大的7,他的累加和是12,以此类推·······直到最后比较3和8的累加和谁大,7和其相加。

73   88   1   02   7   4   44   5   2   6   5


 

0 0