light oj 1031(区间dp入门)

Description

You are playing a two player game. Initially there are n integer numbers in an array and player A and B get chance to take them alternatively. Each player can take one or more numbers from the left or right end of the array but cannot take from both ends at a time. He can take as many consecutive numbers as he wants during his time. The game ends when all numbers are taken from the array by the players. The point of each player is calculated by the summation of the numbers, which he has taken. Each player tries to achieve more points from other. If both players play optimally and player Astarts the game then how much more point can player A get than player B?

Input

Input starts with an integer T (≤ 100), denoting the number of test cases.

Each case contains a blank line and an integer N (1 ≤ N ≤ 100) denoting the size of the array. The next line contains N space separated integers. You may assume that no number will contain more than 4 digits.

Output

For each test case, print the case number and the maximum difference that the first player obtained after playing this game optimally.

Sample Input

2

 

4

4 -10 -20 7

 

4

1 2 3 4

Sample Output

Case 1: 7

Case 2: 10


题意:给出一串数字,A和B只能每次从这串数字的左边或者右边拿数,可以一直拿,A先手,问最后A比B拿到的数字和最多能多多少?

思路:区间dp,用dp[i][j]表示区间i到j之间的A比B拿到的数字和最多的数量,然后状态转移方程有点不好说。。。。这个我是一边写一边突发奇想写出来的o_O???我用的记忆话搜索的方法,这样不需要去考虑递归的顺序啥的,挺简单的。状态转移看我代码吧,比较简洁!!

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<queue>
using namespace std;
typedef long long ll;
int dp[110][110];
int sum[110];
int fdp(int a,int b)
{
    if(dp[a][b]!=-1)return dp[a][b];
    if(a>b)return dp[a][b]=0;
    int max0=-1000000;
    for(int i=a;i<=b;i++)
    {
        max0=max(max0,sum[i]-sum[a-1]-fdp(i+1,b));
        max0=max(max0,sum[b]-sum[i-1]-fdp(a,i-1));
    }
    return dp[a][b]=max0;
}
int main()
{
    int t,o=1;
    scanf("%d",&t);
    while(t--)
    {
        memset(dp,-1,sizeof(dp));
        int n;
        scanf("%d",&n);
        sum[0]=0;
        for(int i=1;i<=n;i++)
            scanf("%d",&dp[i][i]),
            sum[i]=sum[i-1]+dp[i][i];
        fdp(1,n);
        printf("Case %d: %d\n",o++,dp[1][n]);
    }
    return 0;
}

posted @ 2016-04-27 12:50  martinue  阅读(182)  评论(0编辑  收藏  举报