题目大意:
n个数字排成一排,两个人玩游戏。
游戏规则是,每次可以从最左边选择2个以上的数字合并,得分为选中数字的和,合并后生成的新数字为选中数字的和。
直到剩下一个数字,游戏结束。
两个人都希望与对方的最终得分差值尽量大,问先手最终与对方得分的差值为多少。两人足够聪明。
博弈的思想套上DP
考虑dp[i]为把1~i数字预先合并,生成一个新游戏局面,从当前局面开始玩,先手与对放最终得分的差值。
sum[i]为1~i的数字和
这样 d p [ i ] = m a x ( s u m [ j ] − d p [ j ] ) ( i < j ≤ n ) dp[i] = max(sum[j]-dp[j])(i < j \le n) dp[i]=max(sum[j]−dp[j])(i<j≤n)
因为对于dp[i]而言,先手会考虑将1~j数字合并的最佳方案。合并先手得分为sum[j],然后与之后解做差,取最大即为最佳方案。
从n跑到1即可 O(n)求解
代码如下:
#include <iostream>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <climits>
#include <ctime>
#include <cstring>
#include <queue>
#include <stack>
#include <list>
#include <algorithm>
#include <map>
#include <set>
#define LL long long
#define Pr pair<int,int>
#define fread(ch) freopen(ch,"r",stdin)
#define fwrite(ch) freopen(ch,"w",stdout)
using namespace std;
const int INF = 0x3f3f3f3f;
const int mod = 1e9+7;
const double eps = 1e-8;
const int maxn = 212345;
int num[maxn];
LL sum[maxn],dp[maxn];
int main()
{
//fread("");
//fwrite("");
int n;
scanf("%d",&n);
sum[0] = 0;
for(int i = 1; i <= n; ++i)
{
scanf("%d",&num[i]);
sum[i] = sum[i-1]+num[i];
}
LL mx = sum[n];
dp[n] = sum[n];
for(int i = n-1; i >= 1; --i)
{
dp[i] = mx;
mx = max(mx,sum[i]-dp[i]);
}
printf("%lld\n",dp[1]);
return 0;
}