题意:
看一串括号中,能够比配的最大的括号数量。
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, andif a and b are regular brackets sequences, then ab is a regular brackets sequence.no other sequence is a regular brackets sequenceFor 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 [([])].
输入:
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.
样例:
input:
((()))
()()()
([]])
)[)(
([][][)
end
output:
6
6
4
0
6
思路:
还是括号匹配的问题,和上课说的不一样,上课讲的题目是看最少需要添加多少个括号。这道题是说看最多能匹配多少个括号。容易得知,f[i][j]初始化都为0。然后f[i][j]即为字符从i到j最多能匹配到多少个。故可以得知,即从小区间慢慢扩向大区间。整个过程和上课的题目中的石子的合起来的总体相似。即先枚举区间的长度,区间长度从2开始,然后依次枚举区间的起点,和终点。在此处可以对区间进行更新。容易知道如果a[i]与a[j]能匹配起来,则f[i][j]=f[i+1][j-1]+2。其他情况下不会有更新。因为是由小区间增长成大区间,且f[i][j]为最大匹配的,即遍历其中的k,有f[i][j]=max{f[i][j],f[i][k]+f[k+1]f[j]}。最终得到的f[0][n-1]即为所有字符串能匹配起来的最大的数量。
代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
using namespace std;
string a;
int f[120][120];
int main(){
ios::sync_with_stdio(0);
cin>>a;
while(a!="end"){
memset(f,0,sizeof(f));
int n=a.length();
for(int len=2;len<=n;len++){ //子串的长度
for(int i=0;i<=n-len+1;i++){ //起点
int j=i+len-1;
if((a[i]=='('&&a[j]==')')||(a[i]=='['&&a[j]==']')) 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;
cin>>a;
}
return 0;
}