给定n个数字,A和B可以从这串数字的两端任意选数字,一次只能从一端选取。并且A B都尽力使自己选择的结果为最大的,可以理解成A B每一步走的都是最优的。如果A先选择,则A
B差值最大是多少。
思路:用d[i][j]表示当前选手先手走能获得的最大总分数,由于总的分数是一定的,那么状态转移方程为
d[i][j] = sum(i, j) - min( minleft(i+1, j), minright(i, j-1), 0)
其中minleft(i, j)表示min(d[i][j], d[i+1][j] ... d[j][j])
minright(i, j)表示min(d[i][j], d[i][j-1] ... d[i][i])
时间复杂度为O(n*n)
#include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<iostream> #include<algorithm> #include<vector> #include<map> #include<queue> #include<stack> #include<string> #include<map> #include<set> #define eps 1e-6 #define LL long long using namespace std; const int maxn = 100 + 5; const int INF = 0x3f3f3f3f; int A[maxn], d[maxn][maxn], minleft[maxn][maxn], minright[maxn][maxn], s[maxn]; int n; void init() { scanf("%d", &A[0]); s[0] = A[0]; for(int i = 1; i < n; i++) { scanf("%d", &A[i]); s[i] = s[i-1] + A[i]; } } void solve() { for(int i = 0; i < n; i++) { d[i][i] = A[i]; minleft[i][i] = d[i][i]; minright[i][i] = d[i][i]; } for(int j = 2; j <= n; j++) { for(int i = 0; i+j-1 < n; i++) { int mintmp = min(minleft[i+1][i+j-1], minright[i][i+j-2]); d[i][i+j-1] = s[i+j-1] - s[i] + A[i] - min(mintmp, 0); minleft[i][i+j-1] = min(d[i][i+j-1], minleft[i+1][i+j-1]); minright[i][i+j-1] = min(d[i][i+j-1], minright[i][i+j-2]); } } // cout << d[0][n-1] << endl; printf("%d\n", 2*d[0][n-1]-s[n-1]); } int main() { freopen("input.txt", "r", stdin); while(scanf("%d", &n) == 1 && n) { init(); solve(); } return 0; }
时间: 2024-11-11 16:19:14