Brackets(POJ-2955)

Problem 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 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 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

————————————————————————————————————————————————————

题意:给出一串括号字符,求最多的匹配个数。

思路:括号一共有4种,因此可以在读入的时候转为数字,然后再区间 DP

Source Program

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<cstdlib>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<ctime>
#include<vector>
#define INF 0x3f3f3f3f
#define PI acos(-1.0)
#define N 10001
#define MOD 10007
#define E 1e-6
#define LL long long
using namespace std;
char str[N];
int a[N];
int dp[N][N];
int main()
{
    while(scanf("%s",str)!=EOF)
    {
        if(str[0]=='e')
            break;

        int n=strlen(str);
        memset(dp,0,sizeof(dp));


        for(int i=0;i<n;i++)
        {
            if(str[i]=='(')
                a[i]=1;
            if(str[i]==')')
                a[i]=-1;
            if(str[i]=='[')
                a[i]=2;
            if(str[i]==']')
                a[i]=-2;
        }

        for(int len=1;len<n;len++)
        {
            for(int i=0;i<n-len+1;i++)
            {
                int j=i+len;
                if(a[i]+a[j]==0&&a[i]>0)
                    dp[i][j]=dp[i+1][j-1]+2;
                else
                    dp[i][j]=dp[i+1][j-1];

                for(int k=1;k<=j;k++)
                    dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]);
            }
        }
        printf("%d\n",dp[0][n-1]);
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/u011815404/article/details/81805860