POJ2955 - 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 < … < imn, 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

4

6

0

6

题意:

给定一串括号,求其最大匹配长度

分析:

区间dp,用dp[i][j]表示i~j区间上的最大匹配数,据题意可知,当i==j时,dp[i][j]==0,

当i!=j时,假设str[i]和str[j]匹配,dp[i][j]=dp[i+1][j-1]+1,然后在区间k(i~j)之间寻找s[i]和s[k]匹配,状态转移 dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]+1);

注意:

最外层循环从n开始递减,即控制匹配长度由小到大

代码:

#include
#include
#include
using namespace std;

int n;
string str;
int dp[105][105];

bool is_match(int i, int j) {
    if ((str[i] == '('&&str[j] == ')') || (str[i] == '['&&str[j] == ']'))
        return true;
    return false;
}
int solve() {
    n = str.length();
    memset(dp, 0, sizeof(dp));

    for (int i = n - 1; i >= 0; i--)
        for (int j = i + 1; j < n; j++) {
            if (is_match(i, j))
                dp[i][j] = dp[i + 1][j - 1] + 1;
            for (int k = i; k < j; k++)
                dp[i][j] = max(dp[i][j], dp[i][k] + dp[k+1][j]);
        }
    return dp[0][n - 1];
}

int main()
{
    while (cin >> str) {
        if (str == "end")
            break;
        cout << 2 * solve() << endl;
    }
    return 0;
}

 

 

 

 

你可能感兴趣的:(随笔)