hihocoder #1338 : A Game(区间dp)
http://hihocoder.com/problemset/problem/1338
区间dp。
d[l][r]表示[l,r]区间先手取能得到的最大分数。
1 #define bug(x) cout<<#x<<" is "<<x<<endl 2 #define IO std::ios::sync_with_stdio(0) 3 #include <bits/stdc++.h> 4 #define iter ::iterator 5 #define pa pair<int,int> 6 #define pp pair<int,pa> 7 using namespace std; 8 #define ll long long 9 #define mk make_pair 10 #define pb push_back 11 #define se second 12 #define fi first 13 #define ls o<<1 14 #define rs o<<1|1 15 const ll mod=1e9+7; 16 const int N=1e3+10; 17 18 int a[N],b[N]; 19 int d[N][N]; 20 21 int n; 22 23 int dfs(int l,int r){ 24 if(l==r)return a[l]; 25 26 if(d[l][r])return d[l][r]; 27 28 int ans=-1e9; 29 30 ans=max(ans,b[r]-b[l-1]-dfs(l+1,r)); 31 ans=max(ans,b[r]-b[l-1]-dfs(l,r-1)); 32 return d[l][r]=ans; 33 } 34 int main(){ 35 36 scanf("%d",&n); 37 for(int i=1;i<=n;i++){ 38 scanf("%d",&a[i]); 39 b[i]=b[i-1]+a[i]; 40 } 41 printf("%d\n",dfs(1,n)); 42 43 }
或者d[i][j]表示以i为左端点,j为区间长度的区间先手取能得到的最大分数。
1 #define bug(x) cout<<#x<<" is "<<x<<endl 2 #define IO std::ios::sync_with_stdio(0) 3 #include <bits/stdc++.h> 4 #define iter ::iterator 5 #define pa pair<int,int> 6 #define pp pair<int,pa> 7 using namespace std; 8 #define ll long long 9 #define mk make_pair 10 #define pb push_back 11 #define se second 12 #define fi first 13 #define ls o<<1 14 #define rs o<<1|1 15 const ll mod=1e9+7; 16 const int N=1e3+10; 17 18 int n; 19 int a[N],b[N]; 20 int d[N][N]; 21 int main(){ 22 scanf("%d",&n); 23 for(int i=1;i<=n;i++){ 24 scanf("%d",&a[i]); 25 b[i]=b[i-1]+a[i]; 26 d[i][1]=a[i]; 27 } 28 for(int j=2;j<=n;j++){ 29 for(int i=1;i<=n;i++){ 30 d[i][j]=max(b[i+j-1]-b[i-1]-d[i][j-1],b[i+j-1]-b[i-1]-d[i+1][j-1]); 31 } 32 } 33 printf("%d\n",d[1][n]); 34 }