J - Boxes Game -区间dp

  • J - Boxes Game

  •  Gym - 101502J 
  • 题意:a player can take one box from either ends of the line, add the value of the card inside this box to his score, then remove this box from the line.
  • ends of the line,  两端选则其中之一。
  • 注意状态转移,dp里面一直维护的是面对这个区间能够按照规则取出来的最大值 。
  • 不要误以为dp里面存的是某个人的最大值。仅仅是面对这个区间的时候能够取出的最大
  • 所以转移状态的时候就是区间总值减去最大值后剩下的值。然后两种情况中再取一个最大
  • 关键是每个人都最聪明的去取所以要用小区间来维护大区间。
  • #include<bits/stdc++.h>
    using namespace std;
    #define maxn 1555
    int dp[maxn][maxn];
    int t,n,m,a[maxn],sum[maxn];
    int dfs(int l,int r)
    {
        if(dp[l][r]!=-1)
            return  dp[l][r];
        if(l==r)
        {
            return dp[l][r]=a[l];
        }
        int ll=dfs(l+1,r);
        int rr=dfs(l,r-1);
        int total=sum[r]-sum[l-1];
        dp[l][r]=max(total-ll,total-rr);
        return dp[l][r];
    }
    int main()
    {
        cin>>t;
        while(t--)
        {
            cin>>n;
            for(int i=1; i<=n; i++)
            {
                cin>>a[i];
                sum[i]=sum[i-1]+a[i];
            }
            memset(dp,-1,sizeof(dp));
            int ans=dfs(1,n);
            cout<<2*ans-sum[n]<<endl;
        }
        return 0;
    }
    

猜你喜欢

转载自blog.csdn.net/BePosit/article/details/82428015