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 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.
题目简述:
给定一串()[]的字符串,从中选取最长的能够实现“正则”(括号合法匹配)的序列,输出序列长度。多组数据,end结束。
思路:
区间dp。f[i][j]表示从i到j符合题意的子序列的最大长度。因为枚举时,较长的区间需要从较短的区间转移,因此首先枚举区间长度。然后从头开始枚举起点i,因为长度已知了,所以j可以确定。如果i j位置处恰好可以匹配:s[i]=='(' s[j]==')'或者s[i]=='[' s[j]==']',所以此时f[i][j]=f[i+1][j-1]+2.现在考虑区间内部,ij序列可以由包含在ij序列内的子序列i~k k+1~j得到,因此需要再次更新。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
string s;
int n,f[1010][1010];
bool judge(int i,int j)
{
if(s[i]=='['&&s[j]==']') return 1;
if(s[i]=='('&&s[j]==')') return 1;
return 0;
}
int main()
{
while(1)
{
cin>>s;
if(s=="end") break;
n=s.length();
memset(f,0,sizeof(f));
for(int l=1;l<n;l++)
for(int i=0;i+l<n;i++)
{
int j=i+l;
if(judge(i,j))
{
if(j==i+1) f[i][j]=2;
else f[i][j]=f[i+1][j-1]+2;
}
for(int k=i;k<j;k++)
f[i][j]=max(f[i][j],f[i][k]+f[k+1][j]);
}
cout<<f[0][n-1]<<endl;
}
return 0;
}