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
题意:两人博弈,有 n 数排一排,每次只能从两端取,求两个人最终的数字和。
分析:动态规划
方法一:d[i][j] 表示先手从 i 到 j 的最大数字和。
d[i][j]=sum[i][j] - min(d[i+1][j] , d[i][j-1]);
方法二:d[i][j]
(j-i+1)%2==0 d[i][j] 表示先手最大数字和,于是d[i][j]=max(d[i+1][j]+a[i],d[i][j-1]+a[j]);
(j-i+1)%2==1 d[i][j] 表示后手最大数字和,于是d[i][j]=min(d[i+1][j],d[i][j-1]);
方法一:对自己挺无语的直接写了O(n^3)
/* ID: dizzy_l1 LANG: C++ TASK: game1 */ #include<iostream> #include<cstdio> #include<cstring> #define MAXN 110 using namespace std; int d[MAXN][MAXN],sum[MAXN][MAXN],a[MAXN]; int main() { freopen("game1.in","r",stdin); freopen("game1.out","w",stdout); int n,i,j,k; while(scanf("%d",&n)==1) { for(i=1; i<=n; i++) scanf("%d",&a[i]); memset(d,0,sizeof(d)); memset(sum,0,sizeof(sum)); for(i=1; i<=n; i++) { d[i][i]=a[i]; for(j=i; j<=n; j++) { for(k=i; k<=j; k++) { sum[i][j]+=a[k]; } } } for(k=1; k<=n; k++) { for(i=1; i<=n; i++) { for(j=i+k; j<=n; j++) { d[i][j]=sum[i][j]-min(d[i+1][j],d[i][j-1]); } } } printf("%d %d\n",d[1][n],sum[1][n]-d[1][n]); } return 0; }
优化:
方法二:
/* ID: dizzy_l1 LANG: C++ TASK: game1 */ #include<iostream> #include<cstdio> #include<cstring> #define MAXN 110 using namespace std; int d[MAXN][MAXN],a[MAXN]; int main() { freopen("game1.in","r",stdin); freopen("game1.out","w",stdout); int n,i,j,sum; while(scanf("%d",&n)==1) { memset(d,0,sizeof(d)); for(i=1; i<=n; i++) scanf("%d",&a[i]); sum=0; for(i=1; i<=n; i++) sum+=a[i]; for(j=1; j<n; j++) { for(i=1; i<=n; i++) { if((j+1)%2==0) d[i][i+j]=max(d[i+1][i+j]+a[i],d[i][i+j-1]+a[i+j]); else d[i][i+j]=min(d[i+1][i+j],d[i][i+j-1]); } } int ans1,ans2; if(n%2==0) { ans1=d[1][n]; ans2=sum-ans1; } else { ans2=d[1][n]; ans1=sum-ans2; } printf("%d %d\n",ans1,ans2); } return 0; }