poj2955 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[i][j]表示i到j的最大匹配数,先判断一下str[i]和str[j]是不是匹配的,如果是匹配的,那么dp[i][j]=dp[i+1][j-1]+2,因为下面的转移方程无法包含这种情况,所以要特判,然后枚举区间的分割点k,分为两个部分,状态转移方程是dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j])。这里还有一点:使所有括号完全匹配的最少括号等于总长度减去总区间最大匹配数。

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<string>
#include<algorithm>
using namespace std;
#define inf 0x7fffffff
int dp[105][106];
char str[106];
int ok(char a,char b){
    if( (a=='[' && b==']') || (a=='(' && b==')' )    )return 1;
    return 0;
}


int main()
{
    int n,m,i,j,len1,len,k;
    while(scanf("%s",str)!=EOF)
    {
        if(strcmp(str,"end")==0)break;
        len1=strlen(str);
        memset(dp,0,sizeof(dp));
        for(i=0;i<len1-1;i++){
            if(ok(str[i],str[i+1]))dp[i][i+1]=2;
            else dp[i][i+1]=0;
        }
        for(len=3;len<=len1;len++){
            for(i=0;i+len-1<len1;i++){
                j=i+len-1;
                if(ok(str[i],str[j])){
                    dp[i][j]=dp[i+1][j-1]+2;
                }
                for(k=i;k<i+len-1;k++){
                    dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]);
                }
            }
        }
        printf("%d\n",dp[0][len1-1]);

    }
    return 0;
}



posted @ 2015-09-02 12:30  Herumw  阅读(148)  评论(0编辑  收藏  举报