Description
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]表示从i到j这段子串匹配的最大长度,则状态转移方程分两种情况,1.若从i到j-1这些字符中没有一个能与j匹配,则 dp[i][j] = dp[i][j-1],这是显然的;2.若从i到j-1中有字符能与j匹配(可能不止一个,并设他们组成集合为A),则 dp[i][j] = max(dp[i][j],dp[i][k-1]+dp[k+1][j-1]+2)(k属于集合A),加2是因为一旦匹配成功一次长度就会增加2.
1 #include<cstdio> 2 #include<cstring> 3 #include<iostream> 4 #define MAXN 111 5 using namespace std; 6 int dp[MAXN][MAXN]; 7 char str[MAXN]; 8 bool OK(int i,int j){return (str[i] == '(' && str[j] ==')') || (str[i] == '[' && str[j] == ']');} 9 int main(){ 10 //freopen("in.cpp","r",stdin); 11 while(~scanf("%s",str) && strcmp(str,"end")){ 12 memset(dp,0,sizeof(dp)); 13 int len = strlen(str); 14 for(int i = 1;i < len;i ++){ 15 for(int j = i-1;j >= 0;j--){ 16 dp[j][i] = dp[j][i-1]; 17 for(int k = j;k < i;k ++) 18 if(OK(k,i)) dp[j][i] = max(dp[j][i],dp[j][k-1] + dp[k+1][i-1]+2); 19 } 20 } 21 printf("%d ",dp[0][len-1]); 22 memset(str,0,sizeof(str)); 23 } 24 return 0; 25 }