【区间DP】POJ2955.Brackets

题目

POJ2955.Brackets
We give the following inductive definition of a “regular brackets” sequence:

the empty sequence is a regular brackets sequence,
if s s s is a regular brackets sequence, then (s) and [s] are regular brackets sequences, and
if a a a and b b b are regular brackets sequences, then a b ab ab is a regular brackets sequence.
no other sequence is a regular brackets sequence
For instance, all of the following character sequences are regular brackets sequences:

(), [], (()), ()[], ()[()]

while the following character sequences are not:

(, ], )(, ([)], ([(]

Given a brackets sequence of characters a 1 , a 2 … a n a_1,a_2 … a_n a1,a2an, your goal is to find the length of the longest regular brackets sequence that is a subsequence of s. That is, you wish to find the largest m such that for indices i 1 , i 2 , … , i m i_1, i_2, …, i_m i1,i2,,im where 1 ≤ i 1 < i 2 < … < i m ≤ n 1 ≤ i_1 < i_2 < … < i_m ≤ n 1i1<i2<<imn, a i 1 , a i 2 … a i m a_{i1},a_{i2} … a_{im} ai1,ai2aim is a regular brackets sequence.

Given the initial sequence ([([]])], the longest regular brackets subsequence is [([])].

题目就是给出一个字符串,求合法的子序列,注意,可以分开,连续的话是另外的题目

思路

区间DP,我们另dp[i][j]代表字符串从i到j内我们所需要的值,也就是最长的合法子序列,那我们得出递推转移公式:
如果第i个和第j个匹配的话,那么就表示区间 [ i , j ] [i,j] [i,j]的值可以从 [ i + 1 , j − 1 ] [i+1,j-1] [i+1,j1]而来: d p [ i ] [ j ] = d p [ i + 1 ] [ j − 1 ] + 2 dp[i][j]=dp[i+1][j-1]+2 dp[i][j]=dp[i+1][j1]+2
那么我们还得有一个转移就是一个区间 [ i , j ] [i,j] [i,j]的值从两个子区间拼接而成,也就是: d p [ i ] [ j ] = m a x ( d p [ i ] [ j ] , d p [ i ] [ p ] + d p [ p + 1 ] [ j ] ) dp[i][j]=max(dp[i][j],dp[i][p]+dp[p+1][j]) dp[i][j]=max(dp[i][j],dp[i][p]+dp[p+1][j])

代码

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
using namespace std;
string s;
const int N = 207;
int dp[N][N];
int main()
{
    while (cin>>s)
    {
        if (s=="end") return 0;
        memset(dp,0,sizeof(dp));
        int len=s.size();
        for (int k=1;k<len;k++)
        {
            for (int i=0,j=k;j<len;i++,j++)
            {
                if ((s[i]=='('&&s[j]==')')||(s[i]=='['&&s[j]==']'))
                    dp[i][j]=dp[i+1][j-1]+2;
                for (int d=i;d<j;d++)
                    dp[i][j]=max(dp[i][j],dp[i][d]+dp[d+1][j]);
            }
        }
        cout<<dp[0][len-1]<<endl;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值