poj 2955 Brackets (区间dp 括号匹配)

时间:2023-03-08 16:54:57

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 ≤ i1i2 < … < 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

题意:现在已知一个由'()''[]'组成的括号序列 问其中括号匹配数最大的子序列个数

思路:

这里的状态转移是以一个if为基础的,如果s[i]与s[j]匹配,那么明显的dp[i][j] = dp[i+1][j-1];然后在这个基础上枚举分割点k.

状态转移方程:dp[i][j]表示第i~j个字符间的最大匹配对数。

if(s[i] 与 s[j]匹配) dp[i][j] = d[[i+1][j-1] +1;

dp[i][j] = max(dp[i][j],dp[i][k]+dp[k+1][j]);

最后乘2即可

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
#define ll long long int
using namespace std;
inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
inline ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
int moth[]={,,,,,,,,,,,,};
int dir[][]={, ,, ,-, ,,-};
int dirs[][]={, ,, ,-, ,,-, -,- ,-, ,,- ,,};
const int inf=0x3f3f3f3f;
const ll mod=1e9+;
int dp[][];
string s;
int jug(int i,int j){
return (s[i]=='['&&s[j]==']')||(s[i]=='('&&s[j]==')');
}
int main(){
ios::sync_with_stdio(false); while(cin>>s){
if(s=="end") break;
memset(dp,,sizeof(dp));
int n=s.length();
for(int len=;len<=n;len++){
for(int i=;i+len<=n+;i++){
int j=i+len-;
dp[i][j]=dp[i+][j-]+jug(i-,j-);
for(int k=i;k<j;k++)
dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+][j]);
}
}
cout<<*dp[][n]<<endl;
}
return ;
}