lightoj 1031 - Easy Game 【区间dp】

来源:互联网 发布:php培训机构xuefei 编辑:程序博客网 时间:2024/04/30 14:41

Submit Status

Description

You are playing a two player game. Initially there are n integer numbers in an array and playerA 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 A starts the game then how much more point can playerA 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 containsN space separated integers. You may assume that no number will contain more than4 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


题意:两个小孩轮流从一段数字的左边或者右边取走连续的一段,问先手比后手最多多得多少分

尼玛,区间dp居然还有这么玩的==我们可以想到这种题都是小区间合并成大区间的,然而这种类似于博弈的做法实在是让人头疼QAQ,其实倒也不难,既然第一个人的值是有第二个人推导过来的,那么用的值也是第二个人得到的最优值,这么来说,先手后手只是相对概念了==

把[i,j]分成[i,k] [k+1,j]两段,如果取走左边的就是左边的和减去右边那部分后手比先手多的部分,反之亦然


#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;int dp[109][109],sum[109];int t,n,cas;int main(){ //   freopen("cin.txt","r",stdin);    scanf("%d",&t);    cas=1;    while(t--)    {        scanf("%d",&n);        memset(dp,0,sizeof(0));        for(int i=1;i<=n;i++)scanf("%d",&dp[i][i]);        sum[1]=dp[1][1];        for(int i=2;i<=n;i++) sum[i]=sum[i-1]+dp[i][i];        for(int len=1;len<=n;len++)            for(int l=1;l+len<=n;l++)            {                int r=l+len;                dp[l][r]=sum[r]-sum[l-1];                for(int k=l;k<r;k++)                dp[l][r]=max(dp[l][r],max(sum[k]-sum[l-1]-dp[k+1][r],sum[r]-sum[k]-dp[l][k]));            }        printf("Case %d: %d\n",cas++,dp[1][n]);    }    return 0;}


0 0