当前位置:网站首页>One Pass 1258 - Digital Pyramid (Dynamic Programming)
One Pass 1258 - Digital Pyramid (Dynamic Programming)
2022-08-09 03:25:00 【Bamboo Forest Lay-】
Title
Original title linkhttp://ybt.ssoier.cn:8088/problem_show.php?pid=1258[Title Description]
Observe the digital pyramid below.Write a program to find a path that ends anywhere from the highest point to the bottom, so that the sum of the paths passing through the numbers is the largest.Each step can go from the current point to the lower left point or to the lower right point.
In the example above, the path from 13 to 8 to 26 to 15 to 24 yields the largest sum of 86.
[Enter]
The first line contains R (1≤R≤1000), indicating the number of lines.
Each subsequent row contains an integer that is contained in a particular row of this digital pyramid.
All integers supplied are non-negative and not greater than 100.
[Output]
A single line containing the largest possible sum.
[Sample input]
51311 812 7 266 14 15 812 7 13 24 11
[Example output]
86
Thoughts
This problem needs to be done with dynamic programming, not greedy
You can choose the largest of the two branches below each time.This can be done with the help of depth-first search.
Directly using depth-first search will time out, so you need to add memoization
Steps
1. Define variables
const int N=1010;int a[N][N],mk[N][N];int n;
2. Define the deep search function
int dfs(int x,int y){if(x>n) return 0;if(mk[x][y]!=-1) return mk[x][y];return mk[x][y]=max(dfs(x+1,y),dfs(x+1,y+1))+a[x][y];}
3. Main program
int main(){cin>>n;for(int i=1;i<=n;i++){for(int j=1;j<=i;j++){cin>>a[i][j];}}memset(mk,-1,sizeof(mk));cout<
Complete code
#includeusing namespace std;const int N=1010;int a[N][N],mk[N][N];int n;int dfs(int x,int y){if(x>n) return 0;if(mk[x][y]!=-1) return mk[x][y];return mk[x][y]=max(dfs(x+1,y),dfs(x+1,y+1))+a[x][y];}int main(){cin>>n;for(int i=1;i<=n;i++){for(int j=1;j<=i;j++){cin>>a[i][j];}}memset(mk,-1,sizeof(mk));cout<
Novice, please give me more advice
边栏推荐
猜你喜欢
随机推荐
powershell execution strategy
flatMap() :对每个元素执行映射函数并将结果展平
2022-08-08 The fifth group Gu Xiangquan study notes day31-collection-junit unit test
phpStdudy的下载和DVWA的搭建
盘点检索任务中的损失函数
JS 运行机制最全面的一次梳理
JS ES5也可以创建常量?
三箭资本濒临破产?市场陷入1907年恐慌之中?加密监管不可避免
智能计数器控制板的功能及应用有哪些?
【问题记录】pip 安装报错 Failed to establish a new connection
通过kvm创建共享磁盘
当IDEA罢工时
el-popover 内嵌 el-table 后位置错位 乱飘 解决方案
进程和计划任务管理
深度学习:优化器
开发工程师必备————【Day05】UDP协议;进程的并发与并行
剑指 Offer 56 - I. 数组中数字出现的次数
Chapter 2数据分析
opencv学习入门
宝塔实测-在线药店商城源码带WAP版