1. 程式人生 > >ZOJ-4027:Sequence Swapping(DP)

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.

思路:可以想到,對與某個位置為x'(',能與其交換的')'取決於所有位置為y'('的交換情況(y>x)。也就是隻有後面的'('交換過來的')',你才能去交換,不然中間隔著一個'(',是無法交換的。那麼以d[i][j]表示從i開始,把[i,j]裡的')'都與i交換過來的最大值。

當s[i]=')',d[i][j]=d[i+1][j]。

當s[i]='(',d[i][j]=max(d[i][j+1],d[i+1][j]+(sum[j]-sum[i])*v[i])。

#include<bits/stdc++.h>
using namespace std;
const int MAX=1e3+10;
const long long MOD=1e9;
const double PI=acos(-1.0);
typedef long long ll;
char s[MAX];
int v[MAX];
ll d[MAX][MAX],sum[MAX];
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        int n;
        cin>>n;
        scanf("%s",s+1);
        for(int i=1;i<=n;i++)scanf("%d",&v[i]);
        for(int i=1;i<=n;i++)sum[i]=sum[i-1]+(s[i]==')')*v[i];
        ll ans=0;
        memset(d,0,sizeof d);
        for(int i=n;i>=1;i--)
        {
            d[i][n+1]=-1e16;
            if(s[i]==')')
            {
                for(int j=n;j>=1;j--)d[i][j]=d[i+1][j];
                continue;
            }
            for(int j=n;j>=i;j--)d[i][j]=max(d[i][j+1],d[i+1][j]+(sum[j]-sum[i])*v[i]);
            for(int j=i-1;j>=1;j--)d[i][j]=max(d[i][j+1],d[i+1][j]);         //當j<i時,無法交換
            for(int j=n;j>=1;j--)ans=max(ans,d[i][j]);
        }
        printf("%lld\n",ans);
    }
    return 0;
}