POJ2955 -- Brackets
Brackets
| Time Limit:1000 MS |
|
Memory Limit:65536 K |
| Total Submissions:3341 |
|
Accepted:1717 |
Description
We give the following inductive definition of a "regular brackets" sequence:
The empty sequence is a regular brackets sequence, if
SIs a regular brackets sequence, then (
S) And [
S] Are regular brackets sequences, andif
AAnd
BAre regular brackets sequences, then
ABIs 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 charactersA1A2...An, Your goal is to find the length of the longest regular brackets sequence that is a subsequenceS. That is, you wish to find the largestMSuch that for indicesI1,I2 ,...,ImWhere 1 ≤I1 <I2 <... <Im≤N,Ai1Ai2...AimIs 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, intrusive. The end-of-file is marked by a line containing the word "end" and shocould not be processed.
Output
For each input case, the program shocould print the length of the longest possible regular brackets subsequence on a single line.
Sample Input
((()))()()()([]]))[)(([][][)end
Sample Output
66406
Source
Stanford Local 2004
It is also a very classic range dp question. We use dp [I] [j] to represent the maximum number of matching brackets from I to j.
If brackets I cannot match in [I + 1, j], dp [I] [j] = dp [I + 1] [j];
Otherwise, if a k is found in the interval [I, j] So that I and k are paired, the interval is divided into 2 segments, [I + 1, k-1] and [k + 1, j]
So dp [I] [j] = max (dp [I + 1] [j], dp [I + 1] [k-1] + dp [k + 1] [j] + 2)
#include #include
#include
#include
#include
#include
#include
#include
#include
#include
#include using namespace std;char str[110];int dp[110][110];int main(){while (~scanf("%s", str), str[0] != 'e'){int len = strlen(str);memset (dp, 0, sizeof(dp));for (int i = len - 1; i >= 0; --i){for (int j = i + 1; j < len; ++j){dp[i][j] = dp[i + 1][j];for (int k = i + 1; k <= j; ++k){if ((str[i] == '(' && str[k] == ')') || (str[i] == '[' && str[k] == ']')){dp[i][j] = max(dp[i][j], dp[i + 1][k - 1] + dp[k + 1][j] + 2);}}}}printf("%d\n", dp[0][len - 1]);}return 0;}