POJ-2955-Brackets

来源:互联网 发布:淘宝最靠谱的aj店 编辑:程序博客网 时间:2024/06/03 19:21
Brackets
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 6947 Accepted: 3727

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 i1i2, …, imwhere 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

66406

dp[i][j]为串中第 i 个到第 j 个括号的最大匹配数目
那么如果第i个和第j个是一对匹配的括号那么dp[i][j] = dp[i+1][j-1]+2;
dp[i][j] = max(dp[i][j], dp[i][k]+dp[k+1][j]);


dp[][]的MAX开到120就够了,太大会T掉 ,QAQ 

[cpp] view plain copy
  1. #include <iostream>  
  2. #include <stdio.h>  
  3. #include <string.h>  
  4. #include <algorithm>  
  5. #include <queue>  
  6. #include <vector>  
  7. #include <map>  
  8. #include <cmath>  
  9. #include <stdlib.h>  
  10. using namespace std;  
  11. const double PI = acos(-1.0);  
  12. const double eps = 0.1;  
  13. const int MAX = 120;  
  14. const int mod = 1e9+7;  
  15. int dp[MAX][MAX];  
  16. string s;  
  17. int main()  
  18. {  
  19.     while(cin>>s)  
  20.     {  
  21.         if(s=="end")break;  
  22.         memset(dp, 0, sizeof(dp));  
  23.         for(int l = 1; l<(int)s.size(); ++l)  
  24.         {  
  25.             for(int i = 0; i+l<(int)s.size(); ++i)  
  26.             {  
  27.                 int j = i+l;  
  28.                 if((s[i]=='('&&s[j]==')')||(s[i]=='['&&s[j]==']'))  
  29.                     dp[i][j] = dp[i+1][j-1]+2;  
  30.                 for(int k = i; k<j; ++k)  
  31.                     dp[i][j] = max(dp[i][j], dp[i][k]+dp[k+1][j]);  
  32.             }  
  33.         }  
  34.         printf("%d\n", dp[0][(int)s.size()-1]);  
  35.     }  
  36.     return 0;  
  37. }  
原创粉丝点击