区间递推
1.求s数字序列[i,j]内的和sum[i,j]。利用前缀和在O(n)时间内解决
2.dp[i][j[:区间[i,j]内的sum游戏结果 dp[i][j]=max{ sum[i][l]-dp[l+1][j] , sum[l+1][j]-dp[i][l] , i<=l<=j } 。递推式利用了博弈游戏的先手最优性质。
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
#define maxn 1000
#define maxm 10001
#define ll long long
#define sf scanf
#define pf printf
#define INF 0x3f3f3f3f
#define mem(a,b) memset(a,b,sizeof(a))
const ll mod=1000000000;
#define clr(x) memset(x,0,sizeof(x))
using namespace std;
int n,s[maxn];
int sum[maxn];
int dp[maxn][maxn];
int main(){
while(scanf("%d",&n)!=EOF){
if(!n) break;
mem(sum,0),mem(dp,0);
for(int i=1;i<=n;i++){
sf("%d",&s[i]);
sum[i]=(i==1)?s[i]:(sum[i-1]+s[i]);
}
for(int k=0;k<=n;k++){
for(int i=1;i<=n&&i+k<=n;i++){
int j=i+k,tmp=-INF;
if(k==0) { dp[i][j]=s[i]; continue; }
for(int l=i;l<=j;l++){
tmp=max(tmp,sum[l]-sum[i-1]-dp[l+1][j]);
tmp=max(tmp,sum[j]-sum[l-1]-dp[i][l-1]);
}
dp[i][j]=tmp;
}
}
pf("%d\n",dp[1][n]);
}
return 0;
}
递推式优化 按照白书上的递推式,dp[i][j]表示结果中A所得到的分数,dp[i][j]=sum[i][j]-min{dp[i+1][j],dp[i+2][j]...dp[j][j],dp[i][j-1],dp[i][j-2]...dp[i][i],0}
设f[i][j]=min{dp[i+1][j],dp[i+2][j]...dp[j][j]},g[i][j]=min{p[i][j-1],dp[i][j-2]...dp[i][i]} 再简化形式:f[i][j]=min{d[i][j],f[i+1][j]} , g[i][j]=min{d[i][j],g[i][j-1]}
则dp[i][j]=sum[i][j]-min{f[i+1][j],g[i][j-1],0} 复杂度从O(n^3)降为O(n^2)
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
#define maxn 1000
#define maxm 10001
#define ll long long
#define sf scanf
#define pf printf
#define INF 0x3f3f3f3f
#define mem(a,b) memset(a,b,sizeof(a))
const ll mod=1000000000;
#define clr(x) memset(x,0,sizeof(x))
using namespace std;
int n,s[maxn];
int sum[maxn];
int dp[maxn][maxn],g[maxn][maxn],f[maxn][maxn];
int main(){
while(scanf("%d",&n)!=EOF){
if(!n) break;
mem(sum,0),mem(f,0),mem(g,0),mem(dp,0);
for(int i=1;i<=n;i++){
sf("%d",&s[i]);
sum[i]=(i==1)?s[i]:(sum[i-1]+s[i]);
}
for(int k=0;k<n;k++){
for(int i=1;i<=n&&i+k<=n;i++){
int j=i+k;
if(i==j) dp[i][j]=f[i][j]=g[i][j]=s[i];
else{
int tmp=min(f[i+1][j],g[i][j-1]);
tmp=min(tmp,0);
dp[i][j]=sum[j]-sum[i-1]-tmp;
f[i][j]=min(dp[i][j],f[i+1][j]);
g[i][j]=min(dp[i][j],g[i][j-1]);
}
}
}
pf("%d\n",2*dp[1][n]-sum[n]);
}
return 0;
}