[关闭]
@xunuo 2017-01-16T06:18:29.000000Z 字数 2018 阅读 1115

Brackets


Time limit 1000 ms Memory limit 65536 kB

区间DP

来源:
vjudge: D-Brackets
poj: poj 2955 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 < … < 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,用dp[i][j]表示[i,j]区间内符合条件的括号的个数,其状态转移方程为:
dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j])///k为i与j之间的状态
而当s[i],s[j]满足组成一个完整的括号时,
dp[i][j]=dp[i+1][j-1]+2;

完整代码:

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<algorithm>
  4. using namespace std;
  5. int main()
  6. {
  7. char s[110];
  8. int dp[110][110];
  9. while(scanf("%s",s)!=EOF)
  10. {
  11. memset(dp,0,sizeof(dp));
  12. if(s[0]=='e')
  13. break;
  14. int len=strlen(s);
  15. for(int i=0;i<len;i++)
  16. {
  17. if((s[i]=='('&&s[i+1]==')')||(s[i]=='['&&s[i+1]==']'))
  18. dp[i][i+1]=2;
  19. }
  20. for(int l=2;l<len;l++)
  21. for(int i=0;i<len-l;i++)
  22. {
  23. int j=i+l;
  24. if((s[i]=='('&&s[j]==')')||(s[i]=='['&&s[j]==']'))
  25. dp[i][j]=dp[i+1][j-1]+2;
  26. for(int k=i;k<j;k++)
  27. dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]);
  28. }
  29. printf("%d\n",dp[0][len-1]);
  30. }
  31. return 0;
  32. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注