正题
这题区间Dp还是很明显的,考虑对于一个括号序列,要么把它拆成很多个括号序列,要么去掉两端的括号,合并的时候记录下两端的颜色即可。转移明显。
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
using namespace std;
const int N=710;
long long f[N][N][3][3];
const long long mod=1e9+7;
char s[N];
int sta[N],top,last[N],n;
int fx[4]={0,0,1,2};
int fy[4]={1,2,0,0};
void get_ans(int l,int r){
if(l+1==r) {
for(int i=0;i<4;i++) f[l][r][fx[i]][fy[i]]=1;
return ;
}
if(last[r]==l){
get_ans(l+1,r-1);
for(int i=0;i<4;i++){
int x1=fx[i],y1=fy[i];
for(int x2=0;x2<=2;x2++) if(x1!=x2 || x1==0)
for(int y2=0;y2<=2;y2++) if(y2!=y1 || y1==0)
f[l][r][x1][y1]+=f[l+1][r-1][x2][y2];
f[l][r][x1][y1]%=mod;
}
return ;
}
int now=r;
while(now>=l){
get_ans(last[now],now);
now=last[now]-1;
}
now=last[r]-1;
while(now>=l){
for(int x2=0;x2<=2;x2++)
for(int y2=0;y2<=2;y2++)
for(int i=0;i<4;i++){
int x1=fx[i],y1=fy[i];
if(y1!=x2 || x2==0) f[last[now]][r][x1][y2]+=f[last[now]][now][x1][y1]*f[now+1][r][x2][y2]%mod;
}
for(int i=0;i<=2;i++)
for(int j=0;j<=2;j++)
f[last[now]][r][i][j]%=mod;
now=last[now]-1;
}
}
int main(){
scanf("%s",s+1);n=strlen(s+1);
for(int i=1;i<=n;i++){
if(s[i]=='(') sta[++top]=i;
else last[i]=sta[top],top--;
}
get_ans(1,n);
long long ans=0;
for(int i=0;i<=2;i++)
for(int j=0;j<=2;j++)
ans+=f[1][n][i][j];
printf("%lld\n",ans%mod);
}
本文深入探讨了区间动态规划(DP)算法在括号序列问题上的应用。通过将问题分解为子问题并记录颜色信息,实现了高效的求解。文章详细解释了状态转移方程和代码实现细节,为读者提供了一个理解区间DP的良好案例。
488

被折叠的 条评论
为什么被折叠?



