USACO 1.5 Number Triangles

Number Triangles

Consider the number triangle shown below. Write a program that calculates the highest sum of numbers that can be 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.

          7

        3   8

      8   1   0

    2   7   4   4

  4   5   2   6   5

In the sample above, the route from 7 to 3 to 8 to 7 to 5 produces the highest sum: 30.

PROGRAM NAME: numtri

INPUT FORMAT

The first line contains R (1 <= R <= 1000), the number of rows. Each subsequent line contains the integers for that particular row of the triangle. All the supplied integers are non-negative and no larger than 100.

SAMPLE INPUT (file numtri.in)

5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5

OUTPUT FORMAT

A single line containing the largest sum using the traversal specified.

SAMPLE OUTPUT (file numtri.out)

30

题目大意:数字三角形,动态规划(DP)入门题目,说的是有一个一群数字排列成三角形,你现在站在上顶点,现在想要走到底边,每次你可以选择走左下或是右下,每次踩到的数字都累加起来,求最大累加和。
思路:这题搜索不好搞,复杂度2^1000简直开玩笑,仔细思索,发现如果我知道脚下的两个点哪个更优,我就有唯一的行走策略了,那就从下往上推,f[i][j]表示从这点出发到达底边的最大累加和,他可以更新它左上的和右上的,从下往上推一遍答案就出来了,就是f[1][1];代码见下面
 1 /*
 2 ID:fffgrdcc1
 3 PROB:numtri
 4 LANG:C++
 5 */
 6 #include<cstdio>
 7 #include<iostream>
 8 #include<cstring>
 9 using namespace std;
10 int a[1002][1002],f[1002][1002];
11 int main()
12 {
13     freopen("numtri.in","r",stdin);
14     freopen("numtri.out","w",stdout);
15     memset(f,0,sizeof(f));
16     memset(a,0,sizeof(a));
17     int n;
18     scanf("%d",&n);
19     for(int i=1;i<=n;i++)
20     {
21         for(int j=1;j<=i;j++)
22         {
23             scanf("%d",&a[i][j]);
24         }
25     }
26     for(int i=n+1;i>1;i--)
27     {
28         for(int j=1;j<=i;j++)
29         {
30             f[i-1][j]=max(f[i-1][j],f[i][j]+a[i-1][j]);
31             f[i-1][j-1]=max(f[i-1][j-1],f[i][j]+a[i-1][j-1]);
32         }
33     }
34     printf("%d\n",f[1][1]);
35     return 0;
36 }

(这题原来写过,所以写的略快,边界的处理比较粗糙,不过因为我提前把边界外一层留了出来且都设为0,所以不会影响答案)

posted @ 2015-11-27 16:56  徐王  阅读(221)  评论(0编辑  收藏  举报