6581 Number Triangle
2016-05-26 11:30
405 查看
6581 Number Triangle
时间限制:500MS 内存限制:1000K
提交次数:57 通过次数:47
题型: 编程题 语言: G++;GCC
Description
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
作者
admin
最原始的数塔问题,,经典的动态规划问题。状态转移方程:dp[i][j]=max(dp[i-1][j-1],dp[i-1][j])+a[i][j];
其他细节见代码注释:
#include<cstdio> #include<iostream> #include<cstring> #include<cstdlib> #include<cmath> #include<cctype> #include<algorithm> #include<set> #include<map> #include<vector> #include<queue> #include<stack> #include<utility> #define ll long long #define inf 0x3f3f3f3f using namespace std; int a[105][105];//a[i][i]为数塔上点[i][i]处输入的值 int dp[105][105];//dp[i][j]为走到点[i][j]所能得的最大值 int main() { //freopen("input.txt","r",stdin); memset(a,0,sizeof(a)); //初始化数组 memset(dp,0,sizeof(dp)); int n; scanf("%d",&n); //输入数据 for(int i=1;i<=n;i++) { for(int j=1;j<=i;j++) { scanf("%d",&a[i][j]); } } // dp[1][1]=a[1][1]; if(n==1) //n为1就直接输入塔顶数字 { printf("%d\n",dp[1][1]); return 0; } //状态转移方程 for(int i=2;i<=n;i++) { for(int j=1;j<=i;j++) { //走到第a[i][j]位置能得到的最大值dp[i][j]就是等于选择从走到a[i-1][j-1]和走到 //a[i-1][j]中值较大的那种走法里再加上a[i][j]; dp[i][j]=max(dp[i-1][j-1],dp[i-1][j])+a[i][j]; } } // int Max=-1; for(int i=1;i<=n;i++)//扫描塔的最下层,找出最大值 if(dp [i]>Max) Max=dp [i]; printf("%d\n",Max); return 0; }
相关文章推荐
- RunLoop-界面更新
- 穿越雷区--bfs宽度优先搜索
- XMPP与环信的简单介绍
- Vue.js-----轻量高效的MVVM框架(十、父子组件通信)
- dtrace-oracle-vage :吕海波
- SQL数据库添加新账号,只操作指定数据库
- 【kate整理】matlab求商,求余数
- HDU 5701 ——中位数计数——————【思维题】
- Python黑魔法,一行实现并行化
- Ajax 对象创建 兼容各个浏览器 通用方法getHTTPObject.js
- thinkphp框架中,URL传参c/123,接收不到参数的问题
- IDEA Webstorm20161.2最新版本的安装方法
- mysql重置密码
- leetcode_Search a 2D Matrix
- 21V版Office365 管理界面更新
- 【算法题】Leedcode 72
- Xcode那些错
- 设计模式:简单工厂模式
- LeetCode 198: House Robber
- php查询小知识