本文共 2711 字,大约阅读时间需要 9 分钟。
题目链接:
We give the following inductive definition of 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
题目翻译:
我们给出了"常规括号"序列的以下归纳定义:
例如,以下所有字符序列都是常规括号序列:
(), [], (()), ()[], ()[()]
而以下字符序列不是:
(, ], )(, ([)], ([(]
给定一个字符的括号序列1a 2 ...a n,您的目标是找到最长的常规括号序列的长度,该括号序列是s的子序列。也就是说,您希望找到最大的 m,因此对于索引 i 1, i2, ..., im其中 1 = i1 < i2 < ...< im = n, ai1ai2 ...am是一个常规括号序列。
给定初始序列,最长的常规括号子序列为 。([([]])]
[([])]
输入
输入测试文件将包含多个测试用例。每个输入测试用例由一行组成,仅包含字符 、 和 。每个输入测试的长度将在 1 到 100 之间,包括。文件结尾用包含单词"end"的行标记,不应进行处理。(
)
[
]
输出
对于每个输入情况,程序应在一行上打印尽可能长的常规括号子序列的长度。
这道题可以说是最最经典的区间dp题了,也是一道十分好的题。
状态dp[i][j]表示从i区间到j区间内的匹配括号数。
状态转移方程
if(i和j匹配)
dp[i][j]=dp[i+1][j-1]+2
dp[i][j]=max{dp[i][k]+dp[k][j]}k为最优分割点
#include#include #include #include using namespace std;int main(int argc, char** argv) { char str[1005]; int dp[105][105]; while(scanf("%s",str+1)!=EOF&&strcmp(str+1,"end")!=0) { int n=strlen(str+1); memset(dp,0,sizeof(dp)); for(int len=2;len<=n;len++){ for(int i = 1;i<=n;i++){ int j = i+len-1; if(j>n) break; if(str[i]=='['&&str[j]==']'||str[i]=='('&&str[j]==')') dp[i][j]=dp[i+1][j-1]+2; for(int k = i;k
转载地址:http://vifmz.baihongyu.com/