Brackets(括号最大匹配问题(区间dp))
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 代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<vector>
#include<cmath> const int maxn=1e5+;
typedef long long ll;
using namespace std;
string str;
int dp[][];
int main()
{
while(cin>>str)
{
if(str=="end")
{
break;
}
else
{
int n=str.length();
for(int t=;t<n;t++)
{
dp[t][t]=;
}
for(int t=;t<n-;t++)
{
if((str[t]=='['&&str[t+]==']')||(str[t]=='('&&str[t+]==')'))
{
dp[t][t+]=;
}
else
{
dp[t][t+]=;
}
}
for(int r=;r<=n;r++)
{
for(int i=;i<n;i++)
{
int j=i+r-;
if(j>n)
break;
if((str[i]=='['&&str[j]==']')||(str[i]=='('&&str[j]==')'))
{
dp[i][j]=dp[i+][j-]+;
}
else
dp[i][j]=;
for(int k=i;k<j;k++)
{
dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+][j]);
}
}
}
printf("%d\n",dp[][n-]);
}
} return ;
}
最新文章
- 作业七:团队项目——Alpha版本冲刺阶段-07
- 6、面向对象以及winform的简单运用(抽象基类与接口)
- setprecision(int n)等格式函数用法 分类: POJ 2015-06-11 10:56 17人阅读 评论(0) 收藏
- [转载]--用Python 自动安装软件
- Database事件研究
- ZOJ - 3822 Domination (DP)
- mysql 查询各数据库的占用大小
- Torch功能点记录
- 简述JavaScript全局对象
- padStart()方法,padEnd()方法
- 浅谈大数据与hadoop家族
- python自动化之调试
- hdu 3760(2次bfs求最短路)
- C#网页单页小偷源码
- 解决错误: ios property has a previous declaration
- 用dnSpy破解某旅游系统5.2版。
- HDOJ 1159 Common Subsequence【DP】
- 使用Hadoop自己的类操作HDFS
- 项目中遇到的bug
- MVC 登录后重定向回最初请求的 URL FormsAuthentication.RedirectFromLoginPage