IOI'96 - Day 1
Consider the following two-player game played with a sequence of N positive integers (2 <= N <= 100) laid onto a game board. Player 1 starts the game. The players move alternately by selecting a number from either the left or the right end of the sequence. That number is then deleted from the board, and its value is added to the score of the player who selected it. A player wins if his sum is greater than his opponents.
Write a program that implements the optimal strategy. The optimal strategy yields maximum points when playing against the "best possible" opponent. Your program must further implement an optimal strategy for player 2.
PROGRAM NAME: game1
INPUT FORMAT
Line 1: | N, the size of the board |
Line 2-etc: | N integers in the range (1..200) that are the contents of the game board, from left to right |
SAMPLE INPUT (file game1.in)
6 4 7 2 9 5 2
OUTPUT FORMAT
Two space-separated integers on a line: the score of Player 1 followed by the score of Player 2.SAMPLE OUTPUT (file game1.out)
18 11
/*
ID: conicoc1
LANG: C
TASK: game1
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#define Max(a,b) a<b?b:-a
int Size;
int Board[101];
int DP[2][101][101]; //PLayer,Left,Right
int main()
{
FILE *fin,*fout;
fin=fopen("game1.in","r");
fout=fopen("game1.out","w");
fscanf(fin,"%d",&Size);
int i,k,Left,Right;
int temp,Ans1,Ans2,sum;
for(sum=0,i=1;i<=Size;i++){
fscanf(fin,"%d",&Board[i]);
sum+=Board[i];
DP[0][i][i]=DP[1][i][i]=Board[i];
}
for(i=1;i<=Size-1;i++)
DP[0][i][i+1]=DP[1][i][i+1]=Max(Board[i],Board[i+1]);
for(i=2;i<=Size-1;i++){
for(Left=1,Right=Left+i;Right<=Size;Left++,Right++){
for(k=0;k<2;k++){
temp=DP[(k+1)%2][Left+1][Right];
if(temp<0)
Ans1=Board[Left]+abs(DP[k][Left+2][Right]);
else
Ans1=Board[Left]+abs(DP[k][Left+1][Right-1]);
temp=DP[(k+1)%2][Left][Right-1];
if(temp<0)
Ans2=Board[Right]+abs(DP[k][Left+1][Right-1]);
else
Ans2=Board[Right]+abs(DP[k][Left][Right-2]);
DP[k][Left][Right]=Max(Ans1,Ans2);
}
}
}
fprintf(fout,"%d %d\n",abs(DP[0][1][Size]),sum-abs(DP[0][1][Size]));
return 0;
}
一开始写了两个递归函数互相迭代,第四个点超时,改用DP
这个DP还是想复杂了啊= =。。。。
清晰明了一点的方法是:
设sum[i][j]表示从i到j的所有数字和,dp[i][j]表示从i到j这部分的先取者能获得的最大数字和
dp[i][j]=sum[i][j]-min(dp[i][j-1],dp[i+1][j]);