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
Test instructions gives you a string that contains only () [] and asks you how many and characters you can match.
An introductory question for interval DP. DP[I][J] represents the maximum number of matching characters between interval i~j.
if ((s[i]== ' (' &&s[j]== ') ') | | (s[i]== ' [' &&s[j]== ']) ———— >dp[i][j]=dp[i+1][j-1]+2; You know.
The code is as follows:
1#include <cstdio>2#include <algorithm>3#include <cstring>4#include <cmath>5#include <iostream>6 7 using namespacestd;8 Chars[ the];9 intdp[ the][ the];Ten intMain () One { A //freopen ("De.txt", "R", stdin); - while(~SCANF ("%s",&s)) - { the if(s[0]=='e') - Break ; -Memset (DP,0,sizeofDP); - intlen=strlen (s); + for(intk=1; k<len;++k) - { + for(intI=0, j=k;j<len;++i,++j) A { at if((s[i]=='('&&s[j]==')')|| (s[i]=='['&&s[j]==']')) -dp[i][j]=dp[i+1][j-1]+2; - for(intx=i;x<j;x++) -Dp[i][j]=max (dp[i][j],dp[i][x]+dp[x+1][j]); - } - } inprintf"%d\n", dp[0][len-1]); - } to return 0; +}
POJ 2955 Brackets (interval DP primer)