Problem 1004 Number Triangle
Accept: 2267 Submit: 6027
Time Limit: 1000 mSec Memory Limit : 32768 KB
Problem Description
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 44 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.
Input
There are multiple test cases.The first line of each test case 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.
Output
Print a single line containing the largest sum using the traversal specified for each test case.
Sample Input
573 88 1 02 7 4 44 5 2 6 5
Sample Output
30
Source
IOI 95基础dp问题,从上向下动态规划即可。
当前点能够来的点是左上角点或者正上方点,那么动态转移方程:
dp【i】【j】=max(dp【i-1】【j】,dp【i-1】【j-1】)+a【i】【j】
AC代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
int a[1212][1212];
int dp[1212][1212];
int main()
{
int n;
while(~scanf("%d",&n))
{
memset(dp,0,sizeof(dp));
for(int i=0;i<n;i++)
{
for(int j=0;j<=i;j++)
{
scanf("%d",&a[i][j]);
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<=i;j++)
{
if(i==0)
{
dp[i][j]=a[i][j];
}
else
{
if(j==0)dp[i][j]=a[i][j]+dp[i-1][j];
else dp[i][j]=max(dp[i-1][j],dp[i-1][j-1])+a[i][j];
}
}
}
int output=0;
for(int i=0;i<n;i++)
{
output=max(output,dp[n-1][i]);
}
printf("%d\n",output);
}
}