POJ_2955_Brackets

来源:互联网 发布:java驻场开发 编辑:程序博客网 时间:2024/06/05 06:46

Brackets
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 4204 Accepted: 2230

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

66406

Source

Stanford Local 2004

两种括号的匹配问题,这个问题并不能顺序解决

因为两种括号存在交叉的情形,

而且有些情况并不能知道优先匹配哪种括号


这个题目注意分段 dp[st][en]=max{dp[st][mi]+dp[mi+1][en]}

            或者当st与mi匹配时转移到dp[st][en]=max{dp[st+1][mi-1]+2+dp[mi+1][en]}


#include <iostream>#include <stdio.h>#include <string.h>using namespace std;const int M=105;const int IN=1000;char pa[M];int dp[M][M];int main(){    int len;    while(scanf("%s",pa+1)!=EOF)    {        if(pa[1]=='e')            break;        memset(dp,0,sizeof(dp));        len=strlen(pa+1);             //求长度这里注意下开始的位置        for(int l=2;l<=len;l++)            for(int st=1;st<=len-l+1;st++)            {                int co=0;                for(int mi=st;mi<=st+l-1;mi++)                {                    if((pa[st]=='('&&pa[mi]==')')||(pa[st]=='['&&pa[mi]==']'))                        co=max(co,dp[st+1][mi-1]+2+dp[mi+1][st+l-1]);                    else                        co=max(co,dp[st][mi]+dp[mi+1][st+l-1]);                    //cout<<st<<" "<<l<<" "<<mi<<" "<<co<<endl;                }                dp[st][st+l-1]=co;            }        printf("%d\n",dp[1][len]);    }    return 0;}


0 0