[BZOJ2101] [Usaco2010 Dec]Treasure Chest 藏宝箱
Description
Bessie and Bonnie have found a treasure chest full of marvelous gold coins! Being cows, though, they can't just walk into a store and buy stuff, so instead they decide to have some fun with the coins. The N (1 <= N <= 5,000) coins, each with some value C_i (1 <= C_i <= 5,000) are placed in a straight line. Bessie and Bonnie take turns, and for each cow's turn, she takes exactly one coin off of either the left end or the right end of the line. The game ends when there are no coins left. Bessie and Bonnie are each trying to get as much wealth as possible for themselves. Bessie goes first. Help her figure out the maximum value she can win, assuming that both cows play optimally. Consider a game in which four coins are lined up with these values: 30 25 10 35 Consider this game sequence: Bessie Bonnie New Coin Player Side CoinValue Total Total Line Bessie Right 35 35 0 30 25 10 Bonnie Left 30 35 30 25 10 Bessie Left 25 60 30 10 Bonnie Right 10 60 40 -- This is the best game Bessie can play.
Input
* Line 1: A single integer: N * Lines 2..N+1: Line i+1 contains a single integer: C_i
Output
* Line 1: A single integer, which is the greatest total value Bessie can win if both cows play optimally.
Sample Input
30
25
10
35
Sample Output
HINT
(贝西最好的取法是先取35,然后邦妮会取30,贝西再取25,邦妮最后取10)
容易想到N^2区间DP。
设f[i][j]为区间[i, j]先手获得的最大值。
那么f[i, j] = sum[i, j] - min(f[i+1, j], f[i, j-1])。
这样空间过不去, 考虑压缩一维。
我们发现上面的递推式子如果把i从小到大枚举,那么f[i+1, j]是上一层的状态还没有被更新, f[i, j-1]同理。
f[i, i + L] = sum[i, i + L] - min(f[i + 1, i + L], f[i, i + L - 1]。
所以我们可以把第2维压缩掉。
然后只要从小到达转移i就可以正确转移。
#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <cstring> using namespace std; inline int read() { int res=0;char ch=getchar(); while(!isdigit(ch))ch=getchar(); while(isdigit(ch))res=(res<<3)+(res<<1)+(ch^48),ch=getchar(); return res; } #define reg register int n; int a[5005]; int f[5005]; int main() { n = read(); for (reg int i = 1 ; i <= n ; i ++) a[i] = read(); for (reg int i = 1 ; i <= n ; i ++) f[i] = a[i]; for (reg int l = 1 ; l <= n ; l ++) { int sum = 0; for (reg int i = 1 ; i <= 1 + l ; i ++) sum += a[i]; for (reg int i = 1 ; i <= n - l ; i ++) { f[i] = sum - min(f[i+1], f[i]); sum -= a[i]; sum += a[i+l+1]; } } printf("%d\n", f[1]); return 0; }