添加到 @Peter 的动态编程解决方案:
我认为重复性看起来有点像以下:考虑到
Let
的硬币堆栈,表示 Player1 可能获得的最高分数。然后,A[i,..j]
dp[i, j]
dp[i, j] = MAX {
MIN( dp[i+2, j], dp[i+1, j-1], dp[i+2, j-1]) + A[i], //Case when Player2 will try to make the most of it if Player1 picks ith coin.
MIN( dp[i+1, j-1], dp[i, j-2], dp[i+1, j-2]) + A[j], //Case when Player2 will try to make the most of it if Player1 picks the jth coin.
MIN( dp[i+2, j-1], dp[i+1, j-2], dp[i+2, j-2]) + A[i] + A[j] // Case when Player2 will try to make the most of it when Player1 picks both the ith and jth coins.
}
因为只有 N^2 种可能的游戏状态。它可以通过填充大小为 N^2 的 dp 表来实现。
对于 C++ 爱好者:
#include<iostream>
using namespace std;
int Solve(int A[], int N, int **dp, int i, int j){
if(dp[i][j] != -1)
return dp[i][j];
if(j<i)
return 0;
else if(j==i)
return A[i];
else if( (j-i) == 1)
return (A[i] + A[j]);
else{
int opt1 = min(Solve(A, N, dp, i+2, j), Solve(A, N, dp, i+1, j-1));
opt1 = min(opt1, Solve(A, N, dp, i+2, j-1));
int opt2 = min(Solve(A, N, dp, i+1, j-1), Solve(A, N, dp, i, j-2));
opt2 = min(opt2, Solve(A, N, dp, i+1, j-2));
int opt3 = min(Solve(A, N, dp, i+2, j-1), Solve(A, N, dp, i+1, j-2));
opt3 = min(opt3, Solve(A, N, dp, i+2, j-2));
int res = max(opt1+A[i], opt2+A[j]);
res = max(res, opt3+A[i]+A[j]);
dp[i][j] = res;
return res;
}
}
int main(){
int N;
int A[N];
cin >> N;
for(int i=0; i<N; ++i)
cin >> A[i];
int **dp;
dp = new int* [N];
for(int i=0; i<N; ++i)
dp[i] = new int[N];
for(int i=0; i<N; ++i)
for(int j=0; j<N; ++j)
dp[i][j] = -1;
Solve(A, N, dp, 0, N-1);
cout << dp[0][N-1] << endl;
for(int i=0; i<N; ++i)
delete [] dp[i];
delete []dp;
return 0;
}
此外,正如@Peter指出的那样,您对第二个示例的分析是错误的。Player1 实际上有一个策略可以通过获得 102 个硬币来赢得该游戏。