NYOJ-18-The Triangle

描述
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.

输入
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.

输出
Your program is to write to standard output. The highest sum is written as an integer.

样例输入
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5

样例输出
30

逆向思维解题即可。

#include <stdio.h>
#define MAX(a, b) a > b ? a : b

int main(int argc, const char * argv[])
{
    int N;
    int num[5051], value[5051];

    while(~scanf("%d", &N))
    {
        int key = 1;
        for (int i = 1; i <= N; i++)
        {
            for (int j = 1; j <= i; j++)
            {
                scanf("%d", num + key);
                value[key] = num[key];
                key++;
            }
        }

        for (int i = N - 1; i > 0; i--)
        {
            for (int j = i; j > 0; j--)
            {
                value[i * (i - 1) / 2 + j] += MAX(value[(1 + i) * i / 2 + j], value[(1 + i) * i / 2 + j + 1]);
            }
        }

        printf("%d\n", value[1]);
    }

    return 0;
}
全部评论

相关推荐

小谷围鸡肉卷阿姨:+1,腾子投完一动不动
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务