区间dp实战练习

题解报告:poj 2955 Brackets(括号匹配)

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, …, im where 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

6
6
4
0
6
解题思路:经典区间dp,要求找出能配对的括号的最大个数。定义dp[i][j]表示第i到第j个括号的最大匹配数目,那么当第i个括号与第j个括号配对时,dp[i][j]为小的区间最大匹配数加上2即dp[i][j]=dp[i+1][j-1]+2,然后枚举区间[i,j]之间的断点k,合并更新区间[i,j]的最值,最终的答案就是dp[1][length]。时间复杂度为O(n^3)。
AC代码(32ms):
 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstdio>
 4 #include<string.h>
 5 using namespace std;
 6 const int maxn=105;
 7 char str[maxn];int length,dp[maxn][maxn];
 8 bool check(char ch1,char ch2){
 9     return (ch1=='('&&ch2==')')||(ch1=='['&&ch2==']');
10 }
11 int main(){
12     while(~scanf("%s",str+1)&&strcmp(str+1,"end")){
13         memset(dp,0,sizeof(dp));length=strlen(str+1);
14         for(int len=1;len<=length;++len){//枚举区间长度1~length
15             for(int i=1;i<=length-len;++i){//区间起点i
16                 int j=i+len;//区间终点j
17                 if(check(str[i],str[j]))dp[i][j]=dp[i+1][j-1]+2;
18                 for(int k=i;k<j;++k)//区间最值合并
19                     dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]);
20             }
21         }
22         printf("%d\n",dp[1][length]);
23     }
24     return 0;
25 }

猜你喜欢

转载自www.cnblogs.com/acgoto/p/9647496.html
今日推荐