Sequence Swapping(二维dp)

    科技2026-03-01  8

    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.

    #include<bits/stdc++.h> using namespace std; const long long Max=1e5; long long dp[Max][Max]; long long a[Max]; char s[Max]; int main() { int t; cin>>t; while(t--) { long long n; memset(dp,0,sizeof(dp)); cin>>n; scanf("%s",s+1); for(int i=1;i<=n;i++) cin>>a[i]; for(int i=1;i<=n;i++) { if(s[i]=='(') { for(int j=1;j<=n;j++) { long long res=s[i]==')'?a[i]*a[j]:0; dp[i][j]=dp[i][j-1]+res; } } } for(int i=1;i<=n;i++) { long long res=0; for(int j=1;j<=n;j++) { res=max(res,dp[i-1][j]); dp[i][j]+=res; } } long long ans=0; for(int j=1;j<=n;j++) { ans=max(ans,dp[n][j]); } cout<<ans<<endl; } }
    Processed: 0.010, SQL: 9