题目链接:https://vjudge.net/problem/23652/origin
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, …, imwhere 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
输入一个字符串,我们存进str数组,问你最多有多少个合法括号("()"这里是两个),在这里我们可以先把字符串的长度算出来为len,那么问题就是在
0到len-1的区间里
最多有多少个合法
括号,我们定义一个dp数组,dp[i][j]表示在i到j的区间里最多有多少个合法括号,step1:在str[i]==str[j]时,dp[i][j]=dp[i+1][j-1]+2;
然后 step2:我们就在[i,j)(左闭右开区间)里把每一个数设成k,用k来分割区间,把它分割为两个更小的区间,如果dp[i][j]<dp[i][k]+dp[k+1][j]
那么就更新dp[i][j]的值,
注意:step1和step2是都要算的,解释来自:博客链接:https://www.cnblogs.com/Silenceneo-xw/p/5939751.html,因为如果不算step2
那么就会出现"[][]"转移到"]["的情况,如果不算step1,那么答案为0,其实在上面step2里我们不是一个[i,j)的开区间吗?其实我个人认为可以把
step1看成上面开区间的补充(把k=j的情况单独列出,只是这个j有点特别,要特别对待),就是j也看成k,这样k所在区间就是一个左闭右闭区间[i,j]了。
看代码:
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; char str[105]; int dp[105][105],n,m,k,t; int main() { while(fgets(str,105,stdin)) { if(str[0]=='e') break; int len=strlen(str); memset(dp,0,sizeof(dp)); for(int l=1;l<len;l++) { for(int i=0;i<len-l;i++) { int j=i+l; if((str[i]=='('&&str[j]==')')||(str[i]=='['&&str[j]==']')) dp[i][j]=dp[i+1][j-1]+2; for(int k=i;k<j;k++) { if(dp[i][j]<dp[i][k]+dp[k+1][j]) dp[i][j]=dp[i][k]+dp[k+1][j]; } } } printf("%d\n",dp[0][len-1]); } return 0; }