Brackets(区间dp)
阅读原文时间:2023年07月11日阅读:1

Brackets

Time Limit: 1000MS

 

Memory Limit: 65536K

Total Submissions: 8017

 

Accepted: 4257

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 a_1_a_2 … _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 i_1, _i_2, …, _im where 1 ≤i_1 < _i_2 < … < _im ≤ nai_1_ai_2 … _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

Source

Stanford Local 2004

【题目大意】

最大括号匹配

【思路】

区间dp 枚举长度

【code】

#include
#include
#include
using namespace std;
char s[];
int dp[][];
int main()
{
while(gets(s)!=NULL)
{
if(s[]=='e')break;
memset(dp,,sizeof(dp));
int len=strlen(s);
for(int i=;i<=len;i++)
for(int j=,k=i;k<=len;j++,k++)
{
if(s[j]=='('&&s[k]==')'||s[j]=='['&&s[k]==']')
dp[j][k]=dp[j+][k-]+;
for(int p=j;p<=k;p++)
dp[j][k]=max(dp[j][k],dp[j][p]+dp[p+][k]);
}
printf("%d\n",dp[][len-]);
}
return ;
}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器