ZOJ 4027 Sequence Swapping DP+滚动数组优化

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fanbaobao829/article/details/83590519
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll inf=0x3f3f3f3f3f3f3f3f;
const int maxn=2*1e3+5;
char s[maxn];
int a[maxn];
ll dp[2][maxn],sum[maxn],ans;
int main()
{
    int t,n;
    scanf("%d",&t);
    while(t--&&scanf("%d",&n)!=EOF)
    {
        scanf("%s",s+1);
        for(int i=1;i<=n;i++)
            scanf("%d",a+i);
        for(int i=1;i<=n;i++)
        {
            sum[i]=sum[i-1];
            if(s[i]==')')
                sum[i]+=a[i];
        }
        int now,pre;
        now=pre=0;
        ans=0;
        memset(dp,0,sizeof(dp));
        for(int i=n;i;--i)
        {
            if(s[i]==')')
                continue;
            now=pre^1;
            dp[now][n+1]=-inf;
            for(int j=n;j>=i;--j)
                dp[now][j]=max(dp[now][j+1],dp[pre][j]+a[i]*(sum[j]-sum[i]));
            for(int j=i-1;j;--j)
                dp[now][j]=dp[now][j+1];
            ans=max(ans,dp[now][1]);
            pre=now;
        }
        printf("%lld\n",ans);
    }
    return 0;
}
/*
4
6
)())()
1 3 5 -1 3 2
6
)())()
1 3 5 -100 3 2
3
())
1 -1 -1
3
())
-1 -1 -1
*/

猜你喜欢

转载自blog.csdn.net/fanbaobao829/article/details/83590519
今日推荐