题目描述
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 [([])].
输入格式
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.
输出格式
For each input case, the program should print the length of the longest possible regular brackets subsequence on a single line.
输入样例
((()))
()()()
([]])
)[)(
([][][)
end
输出样例
6
6
4
0
6
思路
采用动态规划思想
读入序列到字符数组str中
设状态dp[l][r]为从str[l]到str[r]中最长合法序列长度
则状态转移方程为
dp[l][r]=max(dp[l][k],dp[k+1][r])其中l=<k<=r;
若str[l]与str[r]恰好为一对合法括号,还有
dp[l][r]=max(dp[l][r],dp[l+1][r-1]+2)其中dp[l][r]可为第一个方程求得结果。
则最终结果为dp[1][n]。
代码
#include <iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int inf=1e9;
const int size=100+10;
char str[size];
int dp[size][size];
int main(int argc, char** argv) {
while(scanf("%s",str)&&strcmp(str,"end")!=0)
{
memset(dp,0,sizeof(dp));
int ans=0;
int n=strlen(str);
for(int i=2;i<=n;i++)
{
for(int l=0;l<=n-i;l++)
{
int r=l+i-1;
dp[l][r]=-inf;
for(int k=l;k<r;k++)
{
dp[l][r]=max(dp[l][r],dp[l][k]+dp[k+1][r]);
}
if(str[l]=='('&&str[r]==')'
||str[l]=='['&&str[r]==']')
{
dp[l][r]=max(dp[l][r],dp[l+1][r-1]+2);
}
}
}
printf("%d\n",dp[0][n-1]);
}
return 0;
}