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

相关推荐

今天 15:48
上海交通大学 C++
今天投了小鹏,收到了AI面,大概会问哪些啊?
期末一定及格:总共4个部分,心理测评、行测、然后就是问岗位、对岗位的理解、过往遇到了哪些难点怎么解决,很简单,没有什么特别专业的问题,都是一些综合素质相关的
点赞 评论 收藏
分享
06-10 21:15
门头沟学院 Java
宁阿:好多这种没🧠的公司,他们估计都不知道毕业的人不能给安排实习岗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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