This is a two player game. Initially there are n integer numbers in an array and players A and B get chance to take them. Each player can take one or more numbers from the ' left ' or right ' end of the ' array but cannot take from both to a time. He can take as many consecutive numbers as him 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 the more points from the other. If Both players play optimally and player A starts the game then what much more point can player a get than player B?
Input
The input consists of a number of cases. Each case starts with a line specifying the "integer n " (0 < n≤100), the number of elements in the array. After this, n numbers are given for the game. The Input is terminated by a line where n=0.
Output
For each of the test case, print a number, which represents the maximum difference that the "the" player obtained after playing T His game optimally.
Sample input Output for sample input
Given n a stone, each stone has a fraction, now small partner A and small partner B to play a game, small partner A, each person can choose from scratch or from the tail to take K stone, ask if two people each time according to their best situation to take, the last two people score difference is how much.
Train of thought: Classic interval DP. The situation of interval i,j is expressed by i,j. K is used to indicate a stone, recursive method did not think out, with a memory search to write. Because there may be negative, so more open a vis array to indicate the current interval before the search has not, if the search has been directly to return DP[I][J].
Code:
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std;
int n, num[105], sum[105][105], dp[105][105], vis[105][105];
int dfs (int i, int j) {int ans =-999999999;
if (i > J) return 0;
if (Vis[i][j])//Memory search.
return DP[I][J];
VIS[I][J] = 1;
for (int k = 1; k <= j-i + 1; k + +) {ans = max (ans, sum[i][j]-min (Dfs (i + K, j), Dfs (I, j-k)));
} Dp[i][j] = ans;
return ans;
int main () {while (~SCANF ("%d", &n) && N) {memset (DP, 0, sizeof (DP));
memset (Vis, 0, sizeof (VIS));
for (int i = 0; i < n; i + +) scanf ("%d", &num[i]);
for (int i = 0; i < n; i + +) {int numm = 0;
for (int j = i; J < N; j + +) {Numm + = Num[j];
SUM[I][J] = Numm;
} printf ("%d\n", 2 * DFS (0, n-1)-sum[0][n-1]);
return 0; }
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/