题目描述 Description
如图所示的数字三角形,从顶部出发,在每一结点可以选择向左走或得向右走,一直走到底层,要求找出一条路径,使路径上的值最大。
![](http://codevs.cn/media/image/problem/1220.gif)
输入描述 Input Description
第一行是数塔层数N(1<=N<=100)。
第二行起,按数塔图形,有一个或多个的整数,表示该层节点的值,共有N行。
输出描述 Output Description
输出最大值。
样例输入 Sample Input
5
13
11 8
12 7 26
6 14 15 8
12 7 13 24 11
样例输出 Sample Output
86
数据范围及提示 Data Size & Hint
数字三角形
这是棋盘类型DP非常经典的一道例题吧,要注意的只有两点,第一,N=1的情况,第二,边界时候动态转移方程的变化
动态转移方程:
(j == 1) tower[i][j] += tower[i - 1][j];
(j == i) tower[i][j] += tower[i - 1][j - 1];
其他 ower[i][j] += max(tower[i - 1][j] , tower[i - 1][j - 1]);
(j == i) tower[i][j] += tower[i - 1][j - 1];
其他 ower[i][j] += max(tower[i - 1][j] , tower[i - 1][j - 1]);
代码如下:
/*************************************************************************
> File Name: 数字三角形.cpp
> Author: zhanghaoran
> Mail: chilumanxi@gmail.com
> Created Time: 2015年07月02日 星期四 14时38分47秒
************************************************************************/
#include <iostream>
#include <algorithm>
#include <utility>
#include <cstring>
using namespace std;
int N;
long tower[101][101];
int temp = 0;
int main(void){
cin >> N;
for(int i = 1; i <= N; i ++){
for(int j = 1; j <= i; j ++){
cin >> tower[i][j];
if(i > 1){
if(j == 1)
tower[i][j] += tower[i - 1][j];
else if(j == i)
tower[i][j] += tower[i - 1][j - 1];
else
tower[i][j] += max(tower[i - 1][j] , tower[i - 1][j - 1]);
}
if(i == N){
if(temp < tower[i][j])
temp = tower[i][j];
}
}
}
if(N == 1)
temp = tower[1][1];
cout << temp << endl;
return 0;
}