A - Brackets[括号匹配 区间dp]
Time limit : 1000 ms / Memory limit : 65536 kb
Problem Statement
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
题意
求最长合法括号子序列。(括号匹配)
这里的合法和数学表达式中是一个意思,准确定义如下:
1.空序列是一个合法序列
2.如果s是一个空序列,那么(s) 和 [s]是一个合法序列
3.如果a和b都是合法序列,那么ab是一个合法序列
4.没有其他合法序列
分析
对应定义2、3,我们可以发现,一个合法序列只能由两种方式转变而来,即两个合法序列并列相加 以及 一对括号包含一个合法序列。
欸,“转变”?“转化”?“转移”!莫非是!
状态转移方程!
没错,这题就是dp,区间dp,通过两种方式由合法状态转移为另一种合法状态。
对应两条方程://dp[i][r]代表区间[i,r]内最长合法子序列
1.若区间边界匹配,则 dp[i][r]=max(dp[i][r] , dp[i+1][r-1]+2);
2.以k为分界点,分割为两个合法序列,dp[i][r]=max(dp[i][r] , dp[i][k]+dp[k+1][r]);
这样就遍历了所有情况。
对于遍历过程,要注意一点,最外层枚举区间长度len的原因是,大区间必须从小区间转移而来,所以必须先遍历所有小区间情况。
OK,开搞。
"Talk is Cheap. Show me the Code."
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn = 105;
char str[maxn];
int dp[maxn][maxn];
int main(void)
{
while (scanf("%s", str) && strcmp(str, "end"))// ([([]])] //(()())
{
memset(dp, 0, sizeof(dp));
int Len = strlen(str);
for (int len = 2; len <= Len; len++)
for (int i = 0; i <= Len - len; i++) {
int r = i + len - 1;
if ((str[i]=='(' && str[r]==')') || (str[i] == '[' && str[r] == ']'))
dp[i][r] = max(dp[i][r], dp[i + 1][r - 1] + 2);
for (int k = i; k < r; k++)
dp[i][r] = max(dp[i][r], dp[i][k] + dp[k + 1][r]);
}
printf("%d\n", dp[0][Len-1]);
}
return 0;
}