D-选做题-1
一、题目描述
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.
Sample Input
((()))
()()()
([]])
)[)(
([][][)
end
Sample Output
6
6
4
0
6
二、思路与算法
使用二维dp数组存储区间(i,j)内的合法序列数目,主函数中三个for循环嵌套,分别枚举区间的左端点,区间的右端点,区间内部的分段位置。
注意对于合法序列的定义:空序列、(合法序列)/[合法序列]、合法序列+合法序列。
所以在最内层的循环中,实际上是对i+1到j-1的序列进行计算,之后再对i和j两个位置进行判断,如果两者可以配对,那么dp[i][j]加二。
最后的答案在dp[0][n-1]处,即区间从0到最末尾,整个字符串的合法序列长度。
三、代码实现
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
long long dp[200][200];
string str;
void init(){
for(int i=0;i<200;i++){
for(int j=0;j<200;j++){
dp[i][j]=0;
}
}
}
int main(){
while(1){
cin>>str;
init();
if(str=="end"){break; }
for(int i=str.size()-1;i>=0;i--){ //起始左端点
for(int j=i+1;j<str.size();j++){ //结束右端点
for(int k=i;k<j;k++){ //内部分段
dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]); //注意k的起始和结束,不能漏掉任何情况!
}
if((str[i]=='('&&str[j]==')')||(str[i]=='['&&str[j]==']')){ //如果左右端点能配对上
dp[i][j]=max(dp[i][j],dp[i+1][j-1]+2);
}
}
}
printf("%lld\n",dp[0][str.size()-1]);
}
return 0;
}