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;
}
全部评论

相关推荐

强大的马里奥:不太可能,我校计算机硕士就业率99%
点赞 评论 收藏
分享
野猪不是猪🐗:我assume that你must技术aspect是solid的,temperament也挺good的,however面试不太serious,generally会feel style上不够sharp
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务