poj 2955 Brackets (区间dp基础题)

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

  • the empty sequence is a regular brackets sequence,
  • if s is a regular brackets sequence, then (s) and [s] are regular brackets sequences, and
  • if a and b are regular brackets sequences, then 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 a1a2 … an, 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 i1i2, …, im where 1 ≤ i1 < i2 < … < im ≤ nai1ai2 … aim is a regular brackets sequence.

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

Input

The input test file will contain multiple test cases. Each input test case consists of a single line containing only the characters ()[, and ]; each input test will have length between 1 and 100, inclusive. The end-of-file is marked by a line containing the word “end” and should not be processed.

Output

For each input case, the program should print the length of the longest possible regular brackets subsequence on a single line.

Sample Input

((()))
()()()
([]])
)[)(
([][][)
end

Sample Output

6
6
4
0
6

题目大意:

给你一串由 [ ] ( ) 组成的字符串。问最大匹配长度。

区间dp基础题。

dp[i][j]存储i..j字符串的最大匹配长度。预处理出长度为2的区间匹配长度。

dp[i][j]有两种更新方式:如果s[i]与s[j]匹配,那么dp[i][j]=2+dp[i+1][j-1];接着枚举i..j的所有间断点k:dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j])。

区间dp常规操作:

枚举区间长度、枚举左端点、计算右端点、枚举间断点并merge。

#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

const int maxn=100;

char s[maxn+5];
int dp[maxn+5][maxn+5];

int main()
{
    while(scanf("%s",s+1),s[1]!='e')
    {
        int n=strlen(s+1);

        //预处理出长度为2的区间匹配长度,其余区间全都预置为0
        memset(dp,0,sizeof(dp));
        for(int i=1;i<n;i++)
        {
            if((s[i]=='('&&s[i+1]==')')||(s[i]=='['&&s[i+1]==']'))
                dp[i][i+1]=2;
        }

        //区间DP
        for(int len=3;len<=n;len++)
        {
            for(int left=1;left<=n;left++)
            {
                int right=left+len-1;
                if(right>n)
                    break;
                //两种状态转移情况都可能发生
                if((s[left]=='('&&s[right]==')')||(s[left]=='['&&s[right]==']'))
                    dp[left][right]=2+dp[left+1][right-1];
                for(int k=left;k<right;k++)
                    dp[left][right]=max(dp[left][right],dp[left][k]+dp[k+1][right]);
                //printf("%d %d %d
",left,right,dp[left][right]);
            }
        }

        printf("%d
",dp[1][n]);
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/acboyty/p/9747612.html