P - A Game HihoCoder - 1338

Little Hi and Little Ho are playing a game. There is an integer array in front of them. They take turns (Little Ho goes first) to select a number from either the beginning or the end of the array. The number will be added to the selecter's score and then be removed from the array.

Given the array what is the maximum score Little Ho can get? Note that Little Hi is smart and he always uses the optimal strategy. 

Input

The first line contains an integer N denoting the length of the array. (1 ≤ N ≤ 1000)

The second line contains N integers A1A2, ... AN, denoting the array. (-1000 ≤ Ai≤ 1000) 

Output

Output the maximum score Little Ho can get.

Sample Input
4
-1 0 100 2
Sample Output
99


题意:两个人玩游戏,给出一串数字,每个人每次取第一个或者最后一个数字,其中一个人一直按照最优的方法选择,问他所挑选的数字之和最大是多少。


思路:动态规划思想,枚举每个区间的起点和终点。

代码:

#include<stdio.h>
#include<string.h>
int Max(int x,int y)
{
	if(x>y)
		return x;
	return y;
}
int dp[1010][1010],f[1010],sum[1010];
int main()
{
	int i,j,k,m,n;
	while(scanf("%d",&n)!=EOF)
	{
		memset(dp,0,sizeof(dp));
		memset(f,0,sizeof(f));
		memset(sum,0,sizeof(sum));
		for(i=1;i<=n;i++)
		{
			scanf("%d",&f[i]);
			sum[i]=sum[i-1]+f[i]; 
			dp[i][1]=f[i];
		} 
		for(i=1;i<=n;i++)
		{
			for(j=1;j<=n-i+1;j++)
			{
				dp[j][i]=Max(sum[i+j-1]-sum[j-1]-dp[j][i-1],sum[i+j-1]-sum[j-1]-dp[j+1][i-1]);
			}
		}
		printf("%d\n",dp[1][n]);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/seven_deadly_sins/article/details/79326594