区间DP HDU - 5184 Brackets

来源:互联网 发布:严禁信用卡网络代办 编辑:程序博客网 时间:2024/06/06 14:04

题目:

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 i1i2, …, im where 1 ≤ i1 < i2 < … < im ≤ nai1ai2 … 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

66406

这个题目有一个地方要注意,比如输入的是[][],那么答案应该是4而不是2,

也就是说最外面的2个括号有时可以匹配,有时不能匹配,要看怎么样答案大一些。

然后直接就是记忆化搜索,思路上面没什么难的。

代码:

#include<iostream>#include<string.h>using namespace std;char c[101];int list[101][101];int a;int f(int i, int j){if (list[i][j] >= 0)return list[i][j];if (i >= j)return 0;if (i + 1 == j){if (c[i] == '('&& c[j] == ')' || c[i] == '['&& c[j] == ']')list[i][j] = 1;else list[i][j] = 0;return list[i][j];}if (c[i] == '('&& c[j] == ')' || c[i] == '['&& c[j] == ']')list[i][j] = f(i + 1, j - 1) + 1;for (int k = i; k < j; k++){a = f(i, k) + f(k + 1, j);if (list[i][j] < a)list[i][j] = a;}return list[i][j];}int main(){while (cin.getline(c, 101)){if (c[0] == 'e')break;int l = strlen(c);memset(list, -1, sizeof(list));cout << f(0, l - 1) * 2 << endl;}return 0;}

3 0