POJ 3176 简单DP

Description

The cows don't use actual bowling balls when they go bowling. They each take a number (in the range 0..99), though, and line up in a standard bowling-pin-like triangle like this:
 7 

 3   8 

 8   1   0 

 2   7   4   4 

 4   5   2   6   5
Then the other cows traverse the triangle starting from its tip and moving "down" to one of the two diagonally adjacent cows until the "bottom" row is reached. The cow's score is the sum of the numbers of the cows visited along the way. The cow with the highest score wins that frame.

Given a triangle with N (1 <= N <= 350) rows, determine the highest possible sum achievable.

Input

Line 1: A single integer, N

Lines 2..N+1: Line i+1 contains i space-separated integers that represent row i of the triangle.

Output

Line 1: The largest sum achievable using the traversal rules

Sample Input

5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5

Sample Output

30
题意:输入一个n层的三角形,第i层有i个数,求从第1层到第n层的所有路线中,权值之和最大的路线。
规定:第i层的某个数只能连线走到第i+1层中与它位置相邻的两个数中的一个。

解题思路:DP动态规划,状态转移方程在题意中已经大概给出了,即dp[i][j]=max(dp[i+1][j],dp[i+1][j+1])+dp[i][j];

具体代码:
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int dp[400][400];
int main()
{
	int N,i,j,k;
	while(scanf("%d",&N)!=EOF)
	{
		memset(dp,0,sizeof(dp));
		for(i=1;i<=N;i++)
			for(j=1;j<=i;j++)
				scanf("%d",&dp[i][j]);
		for(i=N-1;i>=1;i--)//从倒数第二层开始查找下面和有下面两个数中最大的,依次往上
			for(j=1;j<=i;j++)
				dp[i][j]=max(dp[i+1][j],dp[i+1][j+1])+dp[i][j];
		printf("%d\n",dp[1][1]);//最后第一个数就是最大的权值和
	}
	return 0;
}



你可能感兴趣的:(POJ 3176 简单DP)