题目链接:
http://poj.org/problem?id=1163
The Triangle
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 45992 | Accepted: 27831 |
Description
7 3 8 8 1 0 2 7 4 4 4 5 2 6 5(Figure 1)
Input
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.
Output
Your program is to write to standard output. The highest sum is written as an integer.
Sample Input
5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
Sample Output
30
Source
IOI 1994
题意:数字三角形。求第一层第一个数加到最后一层两个数的最大和(要求:一个数只能加下一层和他位置相邻的两个数)
思路:最基本的DP之一,本题主要考察状态转移方程。
核心代码:
num[i][j]+=max(num[i+1][j],num[i+1][j+1]);
滚动数组:从倒数第二层开始,加最后一层;一层算完之后,回滚到上一层,知道三角形顶部(相当于从下到上地更新数字三角形,更新之后num[0][0]就是最终答案)
注释的代码,可以帮助更好的理解滚动数组的原理
代码:
<pre name="code" class="cpp">#include<iostream>using namespace std;int main(){int num[200][200],n;int i,j;cin>>n;for(i=0;i<n;i++){for(j=0;j<=i;j++){cin>>num[i][j];}}for (i=n-2;i>=0;i--){for (j=0;j<=i;j++){num[i][j]+=max(num[i+1][j],num[i+1][j+1]);// cout<<num[i][j]<<" ";}//cout<<endl;}cout<<num[0][0]<<endl;return 0;}
革命尚未成功!