POJ2955(KB22-C 区间DP)
Brackets
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
Source
//2017-05-22
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm> using namespace std; int dp[][];//dp[l][r]表示区间l-r中括号匹配数
//若位置l和r匹配,dp[l][r] = max(dp[l][r], dp[l+1][r-1]+2)
//否则,dp[l][r] = max(dp[l][r], dp[l][k]+dp[k+1][r] int main()
{
string str;
while(cin>>str)
{
if(str[] == 'e')break;
int n = str.length();
memset(dp, , sizeof(dp));
for(int len = ; len < n; len++){
for(int i = ; i+len < n; i++){
int j = i+len;
if((str[i] == '(' && str[j] == ')') || (str[i] == '[' && str[j] == ']'))dp[i][j] = max(dp[i][j], dp[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 ;
}
最新文章
- [连载]《C#通讯(串口和网络)框架的设计与实现》- 10.宿主程序详细设计
- 关于JQ toggle 的注意事项
- Mango DS Traning #49 ---线段树3 解题手记
- eclipse ide for java ee developers 开发环境搭建(j2ee)
- 1890. Money out of Thin Air(线段树 dfs转换区间)
- asp.net中的App_GlobalResources和App_LocalResources使用
- IOS中UITableViewCell的重用机制原理
- mysql命令行操作 添加字段,修改字段
- 【翻译Autofac的帮助文档】1.入门指南
- Android -- 自定义view实现keep欢迎页倒计时效果
- PIC32MZ 通过USB在线升级 -- USB HID bootloader
- vuejs2+axios设置
- ATS日志说明
- Bootstrap table 行编辑导航
- C# 发送电子邮件源码片段
- spring boot(三) 集成mybatis
- [转]angular 监听窗口滚动
- MT【72】一个不等式
- python模块中sys.argv[]使用
- Eloquent JavaScript #01# values