问题描述
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 ≤ n, ai1ai2 … aim is a regular brackets sequence.
Given the initial sequence ([([]])], the longest regular
【输入】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.
【输出】
For each input case, the program should print the length of the longest possible regular brackets subsequence on a single line.
【样例输入】`
((()))
()()()
([]])
)[)(
([][][)
end
【样例输出】
6
6
4
0
6
问题分析
括号序列问题,属于区间DP问题,当我们求最少添加括号数时过程如下:
• 长度为1的串的答案一定是1,长度为0的串的答案一定是0。
• 对于某个子序列S = [si,sj]
• 1)f[i][ j]的答案可以由子问题更新而来,即
• f[i][ j] = min{f[i][k] + f[k+1][ j]},(i≤k<j)
• 2)若S形如[S’]或(S’) ,那么f[i][ j] = min{f[i+1][ j-1]}
• 3)若S形如[S’或(S’,那么f[i][ j] = min{f[i+1][ j] + 1}
• 4)若S形如S’]或S’),那么f[i][ j] = min{f[i][ j-1] + 1}
• 上述四种情况取min,得到的答案就是子序列的答案f[i][ j]
• 3,4情况包含于1。可以看作两种理解方式,即两端的括号既可以左右两端匹配。也可以理解为第一种情况的k=1或k=j-1时的情况。
但是,题目中求得的是最大匹配括号数因此本文题不能进行两段枚举,要进行单向枚举遍历,较长的区间从较短的区间转移,首先,在括号可匹配时 dp[i][j]=min(dp[i][j],dp[i+1][j-1]);之后遍历,对于任意大于1的序列均可划分为两部分 dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]);采用反向思想求得最大匹配括号数
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int dp[110][110];
int n;
bool match(char a,char b)
{
if((a=='('&&b==')')||(a=='['&&b==']'))
return true;
return false;
}
int main()
{
string s;
while(cin>>s)
{
memset(dp,0,sizeof(dp));
if(s=="end")
break;
n=s.length();
for(int i=0;i<=n;i++)
dp[i][i]=1;
for(int i=n-2;i>=0;i--)
{
for(int j=i+1;j<n;j++)
{
dp[i][j]=n;
if(match(s[i],s[j]))
dp[i][j]=min(dp[i][j],dp[i+1][j-1]);
for(int k=i;k<j;k++)
dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]);
}
}
cout<<n-dp[0][n-1]<<endl;
}
return 0;
}