2018浙江省赛 ZOJ 4027 Sequence Swapping(dp)

Sequence Swapping

Time Limit: 1 Second       Memory Limit: 65536 KB

BaoBao has just found a strange sequence {<>, <>, , <>} of length  in his pocket. As you can see, each element <> in the sequence is an ordered pair, where the first element  in the pair is the left parenthesis '(' or the right parenthesis ')', and the second element  in the pair is an integer.

As BaoBao is bored, he decides to play with the sequence. At the beginning, BaoBao's score is set to 0. Each time BaoBao can select an integer , swap the -th element and the -th element in the sequence, and increase his score by , if and only if  '(' and  ')'.

BaoBao is allowed to perform the swapping any number of times (including zero times). What's the maximum possible score BaoBao can get?

Input

There are multiple test cases. The first line of the input contains an integer , indicating the number of test cases. For each test case:

The first line contains an integer  (), indicating the length of the sequence.

The second line contains a string  () consisting of '(' and ')'. The -th character in the string indicates , of which the meaning is described above.

The third line contains  integers  (). Their meanings are described above.

It's guaranteed that the sum of  of all test cases will not exceed .

Output

For each test case output one line containing one integer, indicating the maximum possible score BaoBao can get.

Sample Input

4
6
)())()
1 3 5 -1 3 2
6
)())()
1 3 5 -100 3 2
3
())
1 -1 -1
3
())
-1 -1 -1

Sample Output

24
21
0
2

Hint

For the first sample test case, the optimal strategy is to select  in order.

For the second sample test case, the optimal strategy is to select  in order.

【题意】

括号和数字上下对应,若相邻两括号是(),则可以交换(数字也跟着交换),交换时可以获得分数,分数为两数的乘积。

问最大可获得分数

【分析】

用dp[i][j]表示,第i个位置的 '(' 右移到 j 后面时的分数。可以n^2得出(第一次dp)。


易知:i位置的 '(' 要到 j 后面,必须把i->j之间 '(' 移动到 j 之后!

即,1要想到4,必须要使得2到的位置>=4

输出dp矩阵可以发现,就是从第一行任意位置,向下走,或向下一行的任意后边的某位置,走到最后一行的数值和的 最大值

(第二次dp)。


dp[n][j] (1<=j<=n) 的最大值即为答案

【代码】

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int n;
char s[2020];
ll a[2020],dp[2010][2010];
int main()
{
    int T;cin>>T;
    while(T--)
    {
        scanf("%d%s",&n,s+1);
        for(int i=1;i<=n;i++)scanf("%lld",&a[i]);
        for(int i=0;i<=n;i++)for(int j=0;j<=n;j++)dp[i][j]=0;
        for(int i=1;i<=n;i++)if(s[i]=='(')
        {
            for(int j=i+1;j<=n;j++)
            {
                ll res=s[j]==')'?a[i]*a[j]:0ll;
                dp[i][j]=dp[i][j-1]+res;
            }
        }
        for(int i=1;i<=n;i++)
        {
            ll res=0;
            for(int j=1;j<=n;j++)
            {
                res=max(res,dp[i-1][j]);
                dp[i][j]+=res;
            }
        }
        ll ans=0;
        for(int j=1;j<=n;j++)ans=max(ans,dp[n][j]);
        printf("%lld\n",ans);
    }
}
/*
2
6
((()))
2 3 -1 2 -2 1
4
(())
1 2 -1 3
*/


猜你喜欢

转载自blog.csdn.net/winter2121/article/details/80148334