题目链接 ┗|`O′|┛ 嗷~~
给出一个二元组序列,当且仅当Sk=’(’ & Sk+1=’)’ 时,可以交换k 与 k+1 ,并得到值Vk*Vk+1,求能得到的最大值。
因为 ‘(’ 只能与 ‘)’ 交换位置,所以每一个 ‘(’ 都有能到达的最右端的极限位置,现在我们记录在第i个 '(’ 能到达的所有位置 p 中能得到最大值。
记dp[i][j]为第i个括号移动到位置j时得到的最大值。实现的话大致是这样
drep(i,n,1){ //从最后一个括号到第一个括号
drep(pos:all possible position){ //遍历所有可能位置
rep(lastPos : pos+1 - (i-1)-th last possible position){
//根据交换规则,遍历上一个括号可能的位置
getVal; //计算移动到pos得到的值
dp[i][pos]=max(dp[i][pos],val+dp[i+1][lastPos]);
}
}
}
但是这样写复杂度就将会是O(n3),所以需要优化一下。
根据上面那个朴素算法设计我们可以知道,假设将位置i的括号移动到位置j,在计算出这次操作获得的值之后,要与移动到j以后的所有情况比较哪个一是最优解,所以在这里,记dp[i][p]为第i个 ‘(’ 到达 p 及 >p 位置上,得到的最大值,这样再查询的时候就需要比较新加入产生的情况和之前最优的情况,只要O(1)的复杂度就可以得知 >=p位置上的最优解。
在dp过程中为了方便计算,还可以记)对应值的前缀和数组,这样就不用每次都遍历计算获得值。
最后还要注意一点,在第i个括号移动到位置pos时,上一个括号移动到位置pos+1的情况可能时不存在的,因为pos+1小于上一个括号自身的位置。
#include <stdio.h>
#include <climits>
#include <cstring>
#include <time.h>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <utility>
#include <vector>
#include <string>
#define INF 0x3f3f3f3f
#define ll long long
#define Pair pair<int,int>
#define re return
#define getLen(name,index) name[index].size()
#define mem(a,b) memset(a,b,sizeof(a))
#define Make(a,b) make_pair(a,b)
#define Push(num) push_back(num)
#define rep(index,star,finish) for(register int index=star;index<finish;index++)
#define drep(index,finish,star) for(register int index=finish;index>=star;index--)
using namespace std;
const int maxn=1e3+5;
int N;
char store[maxn];
int V[maxn],sum[maxn],pos[maxn];
ll dp[maxn][maxn];
int main(){
//ini
sum[0]=0;
int _;
scanf("%d",&_);
while(_--){
int all=1,cou=1;
scanf("%d",&N);
scanf("%s",store+1);
rep(i,1,N+1){
scanf("%d",&V[i]);
if(store[i]=='('){
pos[all++]=i;
}else{
sum[cou]=sum[cou-1]+V[i];
cou++;
}
}
pos[all]=0;
all--;
mem(dp,0);
drep(i,all,1){
//select i-th (
int nowPos=pos[i];
for(register int p=N-(all-i);p>=nowPos;p--){
ll temp=dp[i+1][p+1];
if(p+1<pos[i+1]){
temp=dp[i+1][pos[i+1]];
}
//position we can move to
dp[i][p]=temp+1LL*(sum[p-i]-sum[nowPos-i])*V[nowPos];
if(p<N-(all-i))
dp[i][p]=max(dp[i][p],dp[i][p+1]);
}
}
printf("%lld\n",dp[1][pos[1]]);
}
re 0;
}