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

Sample Output

6
6
4
0
6

题意:求符合条件的最长的子字符串长度。

题解:简单区间dp,看代码解释

#include <iostream>
#include <cstring>
using namespace std;
const int MAX = 520;
int dp[MAX][MAX];
int  main(){
	string s;
	while(cin >> s){
		memset(dp,0,sizeof(dp));//初始化别忘记
		if(s=="end") break;
		string ss="#";
		ss+=s;
		int l=ss.size();
		for (int i = 2; i < l ;i++){//暴力枚举每一个区间
			for (int j = 1;j+i-1 < l;j++){//注意是j+i-1<l 不要越界,越界也会过,很迷
				int r=j+i-1;//区间长度i来控制
				if(ss[j]=='('&&ss[r]==')'||ss[j]=='['&&ss[r]==']'){
					if(r-1==j) dp[j][r]=2;//看两个符号之间是否有别的符合的符号
					else dp[j][r]=dp[j+1][r-1]+2;
				}
				int ans=0;//求最大值,初始化为0
				for (int k = j;k <= r;k++){//枚举区间
					ans=max(ans,dp[j][k]+dp[k+1][r]);
				}
				dp[j][r]=ans;
			}
		}
	cout << dp[1][l-1] << endl;
	}
	return 0;
}