动态规划(区间dp)

 

B - Brackets

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 i1, i2, …, 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
6
6
4
0
6

题解:区间dp,先确定状态,区间[i,j]就是状态,dp(i,j)表示区间[i,j]里最长的正则串,对于i点有两种情况,

1...后面没有与之匹配的,那么不选i点的字符,直接转移状态dp[i][j]=d[i+1][j]

2...从i+1开始一直到j,如果有与i点匹配的字符(设该点为k),就选i,k两点的字符串,并把[i,j]划分为两部分,[i+1,k-1]和[k+1,j]

则可以转移状态dp[i][j]=max(dp[i][j],dp[i+1][k-1]+dp[k+1][j]+2);

AC代码:

#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
    ios::sync_with_stdio(0),cin.tie(0);
    string s;
    int dp[101][101];
    while(cin>>s&&s!="end")
    {
        memset(dp,0,sizeof dp);
        for(int i=s.size()-1;i>=0;i--)//左端点从最右边开始遍历到最左边
            for(int j=i+1;j<s.size();j++)
            {
                dp[i][j]=dp[i+1][j];//没有匹配的也要转移状态
                for(int k=i+1;k<=j;k++)
                    if(s[i]=='('&&s[k]==')'||s[i]=='['&&s[k]==']')//第k个字符与前面的第i个字符匹配
                      dp[i][j]=max(dp[i][j],dp[i+1][k-1]+dp[k+1][j]+2);
            }
        cout<<dp[0][s.size()-1]<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/shaohang_/article/details/81104884