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] is 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 is regular brackets sequences:
(), [], (()), ()[], ()[()]
While the following character sequences is not:
(, ], )(, ([)], ([(]
Given a brackets sequence of characters a1a2 ... An, your goal are to find the length of the longest regular brackets sequence, which is a subsequence of s. That's, you wish to find the largest m such this 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 would contain multiple test cases. Each input test case consists of a single line containing only the characters (
, )
, [
, and ]
; each input t EST would have length between 1 and inclusive. The End-of-file is marked by a line containing the word "end" and should not being 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
((())) () () () () ([][][)
Sample Output
66406
The number of parentheses that can be correctly matched by parentheses
DP (I,J) indicates the correct number of parentheses within the interval ij
DP (I,J) =MAX{DP (i+1,j-1) +2 (only if outer brackets match), DP (I,K) +DP (k,j) (inner bracket Check)}
#include"iostream"#include"CString"using namespacestd;intdp[ the][ the];stringA;voidWork () {intlen=a.length (); //cout<<len<<endl;Memset (DP,0,sizeof(DP)); intans=0; for(intI=0; i<len;i++) { for(intj=0, k=i;k<len;k++,j++) { if((a[j]=='('&&a[k]==')')|| (a[j]=='['&&a[k]==']')) Dp[j][k]=dp[j+1][k-1]+2; for(intt=j+1; t<k;t++) if(dp[j][t]+dp[t][k]>Dp[j][k]) dp[j][k]=dp[j][t]+Dp[t][k]; if(Dp[j][k]>ans) ans=Dp[j][k]; }} cout<<ans<<Endl;}intMain () { while(cin>>a) {if(a=="End") Break; Work (); } return 0;}
o (o_o) o
The fifth week of intensive training dynamic programming J-Brace matching