Number Triangles
2024-08-29 15:07:33
题目描述
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.
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.
输入
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.
输出
A single line containing the largest sum using the traversal specified.
样例输入
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
样例输出
30
分析:
我就说是个DP题,递什么归递归。
设dp[i][j]表示从底层走到达坐标[i][j]的最大值,从底向上扫,状态转移方程为dp[i][j]+=max(dp[i+1][j],dp[i+1][j+1])。
#include <iostream>
#include <string>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#define range(i,a,b) for(int i=a;i<=b;++i)
#define rerange(i,a,b) for(int i=a;i>=b;--i)
#define fill(arr,tmp) memset(arr,tmp,sizeof(arr))
using namespace std;
int n,dp[][];
void init(){
cin>>n;
range(i,,n)range(j,,i)cin>>dp[i][j];
rerange(i,n-,)
range(j,,i)dp[i][j]+=max(dp[i+][j],dp[i+][j+]);
}
void solve(){
cout<<dp[][]<<endl;
}
int main() {
init();
solve();
return ;
}
最新文章
- HQL多种查询实现
- [游戏模版4] Win32 显示鼠标位置
- Python中的模块与包
- visual studio 2013使用技巧
- MVC HtmlHelper
- apache开源项目--Apache Drill
- angularjs填写表单
- Windows 安装Django并创建第一个应用
- vuejs 三级联动
- 一个利用扩展方法的实例:AttachDataExtensions
- html拨打电话、发送短信、发送邮件的链接写法
- NOIP 2015
- windows下mysql 5.7以上版本安装及遇到的问题
- windows下连接smb服务器
- linux查看tomcat安装路径
- swaggerui集成oauth implicit
- html 響應式web設計
- SQL Server 常用函数使用方法(持续更新)
- (转)Java 中正确使用 hashCode 和 equals 方法
- c#简单案例--单位转换器