POJ 2955 Brackets(括号匹配一)

题目链接:http://poj.org/problem?id=2955

题目大意:给你一串字符串,求最大的括号匹配数。

解题思路:

设dp[i][j]是[i,j]的最大括号匹配对数。

则得到状态转移方程:

if(str[i]=='('&&str[j]==')'||(str[i]=='['&&str[j]==']')){
  dp[i][j]=dp[i+1][j-1]+1;
}
dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]) ,(i<=k<j)

代码:

 1 #include<cstdio>
 2 #include<cmath>
 3 #include<cctype>
 4 #include<cstring>
 5 #include<iostream>
 6 #include<algorithm>
 7 #include<vector>
 8 #include<queue>
 9 #include<set>
10 #include<map>
11 #include<stack>
12 #include<string>
13 #define lc(a) (a<<1)
14 #define rc(a) (a<<1|1)
15 #define MID(a,b) ((a+b)>>1)
16 #define fin(name)  freopen(name,"r",stdin)
17 #define fout(name) freopen(name,"w",stdout)
18 #define clr(arr,val) memset(arr,val,sizeof(arr))
19 #define _for(i,start,end) for(int i=start;i<=end;i++)
20 #define FAST_IO ios::sync_with_stdio(false);cin.tie(0);
21 using namespace std;
22 typedef long long LL;
23 const int N=5e2+5;
24 const int INF=0x3f3f3f3f;
25 const double eps=1e-10;
26 
27 int dp[N][N];
28 char str[N];
29 
30 int main(){
31     while(~scanf("%s",str)&&strcmp(str,"end")){
32         int n=strlen(str);
33         memset(dp,0,sizeof(dp));
34         for(int len=1;len<n;len++){
35             for(int i=0;i+len<n;i++){
36                 int j=i+len;
37                 if(str[i]=='('&&str[j]==')'||(str[i]=='['&&str[j]==']')){
38                     dp[i][j]=dp[i+1][j-1]+1;
39                 }
40                 for(int k=i;k<j;k++){
41                     dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]);
42                 }
43             }
44         }
45         printf("%d
",dp[0][n-1]*2);
46     }
47     return 0;
48 }
原文地址:https://www.cnblogs.com/fu3638/p/8843534.html