POJ - 3176 Cow Bowling (Dp初步,记忆化搜索递推)

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

Hint

Explanation of the sample: 

          7

         *

        3   8

       *

      8   1   0

       *

    2   7   4   4

       *

  4   5   2   6   5

The highest score is achievable by traversing the cows as shown above.

 题意,从三角顶端走到最后一行经历的最大值;

这里递归效率太低,而且明显会超时。在此用递推和记忆化搜索两种方法

递推(时间复杂度为O(n^2)

for(int j=1;j<=n;j++)
{
   d[n][j]=a[n][j];
}
for(int i=n-1;i>=1;i--)
{
	for(int j=1;j<=i;j++)
	{
		d[i][j]=a[i][j]+max(d[i+1][j],d[i+1][j+1]);
	}
}

记忆化搜索

memset(d,-1,sizeof(d));//初始化都为-1
int solve(int i,int j)
{
	if(d[i][j]>=0)//计算过
		return d[i][j];
	return d[i][j]=a[i][j]+(i==n?0:max(solve(i+1,j),solve(i+1,j+1)));
} 

程序依旧是递归,但是将计算结果保存在数组d中,

ac代码

#include<iostream>
#include<cstdio>
using namespace std;

int main()
{
	int a[360][360],d[360][360];
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=i;j++)
		{
		 	cin>>a[i][j];
		}
	}
/*	for(int i=0;i<n;i++)
	{
		for(int j=0;j<=i;j++)
		{
		 	cout<<a[i][j];
		}
		cout<<endl;
	}*/
	for(int i=1;i<=n;i++)
	{
		d[n][i]=a[n][i];
	}
	for(int i=n;i>1;i--)
	{
		for(int j=1;j<i;j++)
		{
			if(d[i][j]>d[i][j+1])
				d[i-1][j]=d[i][j]+a[i-1][j];
			else 
				d[i-1][j]=d[i][j+1]+a[i-1][j];
		}
	}
	cout<<d[1][1];
	
}

猜你喜欢

转载自blog.csdn.net/henu_xujiu/article/details/81135240