程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Light OJ 1031---Easy Game(區間DP),oj1031---easy

Light OJ 1031---Easy Game(區間DP),oj1031---easy

編輯:C++入門知識

Light OJ 1031---Easy Game(區間DP),oj1031---easy


題目鏈接

http://lightoj.com/volume_showproblem.php?problem=1031

 

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 A starts 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

Output for Sample Input

2

 

4

4 -10 -20 7

 

4

1 2 3 4

Case 1: 7

Case 2: 10

 

題意:有n個數排成一行,現在A和B兩人從兩端取任意個數(每次至少取一個),直到取完所有的數,A先取,求A取得數的和比B大多少?

思路:區間DP,dp[i][j] 表示區間i~j A取得數的和比B大多少,那麼可以這樣分析:對於區間i~j  A先取sum[k]-sum[i-1]或sum[j]-sum[k](只能從兩端取),然後該B取了,即對於區間k+1~j和i~k  DP轉換為B比A大多少了,所以狀態轉移方程為 dp[i][j]=max(dp[i][j],max(sum[k]-sum[i-1]-dp[k+1][j],sum[j]-sum[k]-dp[i][k])); 

代碼如下:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
int sum[105];
int dp[105][105];   ///A比B大多少?

int main()
{
    int T,Case=1;
    int n;
    cin>>T;
    while(T--)
    {
        sum[0]=0;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&sum[i]);
            sum[i]+=sum[i-1];
        }
        memset(dp,0,sizeof(dp));
        for(int i=1;i<=n;i++)
            dp[i][i]=sum[i]-sum[i-1];
        for(int len=1;len<n;len++)
        {
            for(int i=1;i<=n;i++)
            {
                if(i+len>n) break;
                dp[i][i+len]=sum[i+len]-sum[i-1];
                for(int k=i;k<i+len;k++)
                {
                    dp[i][i+len]=max(dp[i][i+len],max(sum[k]-sum[i-1]-dp[k+1][i+len],sum[i+len]-sum[k]-dp[i][k]));
                }
            }
        }
        printf("Case %d: %d\n",Case++,dp[1][n]);
    }
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved