您的位置:首页 > 其它

POJ 2955 Brackets 【区间DP】

2017-10-25 12:02 381 查看
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

对于括号匹配问题而言,实际上[]与()别无二致。

我不知道贪心思想怎么解决,是否是根据栈能搞出什么操作。

区间DP的话,前两层循环和常规操作别无二致。第一层枚举区间,第二层枚举坐标。同样的第三层进行更新操作,也顺手根据当前匹配情况来做些许改动。

if ((str[i] == '['&&str[j] == ']') || (str[i] == '('&&str[j] == ')'))

dp[i][j]=max(dp[i][j],dp[i+1][j−1]+2);

本区间DP与常规题唯一的不同就是,括号一旦匹配,一次性+2。

值得注意的是字符串的下标是从零开始~

#include<iostream>
#include<cstring>
#include<algorith
4000
m>
using namespace std;
#define Irish_Moonshine main
const int maxn = 105;
int dp[maxn][maxn];
char str[maxn];
char stop_end[4] = "end";
int Irish_Moonshine()
{
while (cin >> str)
{
memset(dp, 0, sizeof(dp));
int len = strlen(str);
if (str[0] == 'e')
return 0;
/*  for (int i = 0; i < len; i++)
{
dp[i][i] = 0;
}*/
for (int k = 2; k <= len; k++)//区间长度
{
for (int i = 0; i < len - k + 1; i++)//左端点
{
int j = k + i - 1;//区间长度为K,右端点j
for (int tmp = i; tmp < j; tmp++)
{
dp[i][j] = max(dp[i][j], dp[i][tmp] + dp[tmp + 1][j]);
if ((str[i] == '['&&str[j] == ']') || (str[i] == '('&&str[j] == ')'))
dp[i][j] = max(dp[i][j], dp[i + 1][j - 1] + 2);
}
}
}
cout << dp[0][len - 1] << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: