Codeforces149D(计数区间dp)

题意:

给出串规律的括号(括号是匹配好的)比如说 ( ( ) ( ) )   这个括号的真确匹配是 第一个和最后一个、第二个和第三个、第四个和第五个。

现在要给括号染色,给出这些条件:
1、括号可以不染色、染蓝色、染红色。

2、匹配的括号不能同时染色,但其中一个必须染色。

3、相邻的括号不能染同种颜色,允许都不上色。

题解:

记忆优化的好处,要什么状态加上什么状态,然后一次新搜索,记录。这题用递推挺难写的。

状态:dp[i][j][k][t] 左(i) 右(j)区间括号匹配情况为k,t 时最大的方案数。

#include<iostream>
#include<math.h>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<vector>
#include<map>
using namespace std;
typedef long long lld;
const int oo=0x3f3f3f3f;
const lld OO=1LL<<61;
const lld MOD=1000000007;
#define eps 1e-6
#define maxn 705
lld dp[maxn][maxn][3][3];
char str[maxn];
int mat[maxn],stack[maxn];
int n;

void Match()
{
    int top=0;
    for(int i=1;i<=n;i++)
    {
        if(str[i]=='(')
            stack[++top]=i;
        else
        {
            mat[i]=stack[top];
            mat[stack[top]]=i;
            --top;
        }
    }
}

void dfs(int i,int j)
{
    if(i+1==j)
    {
        dp[i][j][0][1]=1;
        dp[i][j][1][0]=1;
        dp[i][j][0][2]=1;
        dp[i][j][2][0]=1;
        return ;
    }
    if(mat[i]==j)
    {
        dfs(i+1,j-1);
        for(int l=0;l<3;l++)
        {
            for(int r=0;r<3;r++)
            {
                if(l!=1)
                    dp[i][j][0][1]=(dp[i][j][0][1]+dp[i+1][j-1][l][r]+MOD)%MOD;
                if(r!=1)
                    dp[i][j][1][0]=(dp[i][j][1][0]+dp[i+1][j-1][l][r]+MOD)%MOD;
                if(l!=2)
                    dp[i][j][0][2]=(dp[i][j][0][2]+dp[i+1][j-1][l][r]+MOD)%MOD;
                if(r!=2)
                    dp[i][j][2][0]=(dp[i][j][2][0]+dp[i+1][j-1][l][r]+MOD)%MOD;
            }
        }
    }
    else
    {
        int m=mat[i];
        dfs(i,m);
        dfs(m+1,j);
        for(int l=0;l<3;l++)
        {
            for(int r=0;r<3;r++)
            {
                for(int x=0;x<3;x++)
                {
                    for(int y=0;y<3;y++)
                    {
                        ///相邻的括号不能有同种颜色
                        if(x==1&&y==1)continue;
                        if(x==2&&y==2)continue;

                        dp[i][j][l][r]=(dp[i][j][l][r]+(dp[i][m][l][x]*dp[m+1][j][y][r])%MOD+MOD)%MOD;
                    }
                }
            }
        }
    }
}

int main()
{
    while(scanf("%s",str+1)!=EOF)
    {
        n=strlen(str+1);
        memset(dp,0,sizeof dp);
        Match();
        dfs(1,n);
        lld ans=0;
        for(int l=0;l<3;l++)
            for(int r=0;r<3;r++)
                ans=(ans+dp[1][n][l][r]+MOD)%MOD;
        cout<<ans<<endl;
    }
    return 0;
}
/**
(())
(()())
()


*/







你可能感兴趣的:(dp,codeforces)