http://poj.org/problem?id=2955
Description
We give the following inductive definition of 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
经典的区间DP模型--最大括号匹配数。如果找到一对匹配的括号[xxx]oooo,就把区间分成两部分,一部分是xxx,一部分是ooo,然后以此递归直到区间长度为1或者为2.
状态转移方程:dp[i][j] = min(dp[i+1][j],dp[i+1][k-1]+dp[k+1][j]+1)(i<=k<=j&&i和k是一对括号)
方法一:记忆化搜索写法
#include <stdio.h> #include <iostream> #include <string.h> #include <algorithm> using namespace std; char a[105]; int dp[105][105]; int solve(int x,int y) { if(x>=y) return 0; if(dp[x][y]) return dp[x][y]; dp[x][y]=solve(x+1,y); for(int i=x+1;i<=y;i++) { if((a[x]=='('&&a[i]==')')||(a[x]=='['&&a[i]==']')) dp[x][y]=max(dp[x][y],solve(x+1,i-1)+2+solve(i+1,y)); } return dp[x][y]; } int main() { while(~scanf("%s",a+1)) { if(strcmp(a+1,"end")==0) break; memset(dp,0,sizeof(dp)); int n=strlen(a+1); printf("%d\n",solve(1,n)); } return 0; }
方法二:直接DP
#include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> using namespace std; char a[105]; int dp[105][105]; int main() { while(~scanf("%s",a+1)) { if(strcmp(a+1,"end")==0) break; memset(dp,0,sizeof(dp)); int n=strlen(a+1); /* for(int i=1;i<=n;i++) cout <<a[i]; cout <<"**"<<endl;*/ for(int i=n-1; i>=0; i--) for(int j=i+1; j<=n; j++) { dp[i][j]=dp[i+1][j]; for(int k=i+1; k<=j; k++) if((a[i]=='('&&a[k]==')')||(a[i]=='['&&a[k]==']')) dp[i][j]=max(dp[i][j],dp[i+1][k-1]+dp[k+1][j]+2); } /*for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) printf("%d ",dp[i][j]); printf("\n"); }*/ printf("%d\n",dp[1][n]); } return 0; }