poj 2955 Brackets 区间dp
给一堆括号, 问最多有多少个是匹配的。
依然是区间dp, 直接记忆化搜索就可以。
#include <iostream> #include <vector> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <map> #include <set> #include <string> #include <queue> using namespace std; #define pb(x) push_back(x) #define ll long long #define mk(x, y) make_pair(x, y) #define lson l, m, rt<<1 #define mem(a) memset(a, 0, sizeof(a)) #define rson m+1, r, rt<<1|1 #define mem1(a) memset(a, -1, sizeof(a)) #define mem2(a) memset(a, 0x3f, sizeof(a)) #define rep(i, a, n) for(int i = a; i<n; i++) #define ull unsigned long long typedef pair<int, int> pll; const double PI = acos(-1.0); const double eps = 1e-8; const int mod = 1e9+7; const int inf = 1061109567; const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; char s[105]; int dp[105][105]; int judge(int l, int r) { if(s[l] == '('&&s[r]==')') return 2; if(s[l]=='['&&s[r]==']') return 2; return 0; } int dfs(int l, int r) { if(~dp[l][r]) return dp[l][r]; dp[l][r] = 0; if(l>r) return 0; if(l == r) return 0; if(r-l == 1) { return dp[l][r] = judge(l, r); } if(judge(l, r)) dp[l][r] = dfs(l+1, r-1)+2; for(int i = l; i<=r; i++) { dp[l][r] = max(dp[l][r], dfs(l, i)+dfs(i+1, r)); } return dp[l][r]; } int main() { while(scanf("%s", s+1)) { mem1(dp); int len = strlen(s+1); if(!strcmp(s+1, "end")) break; else printf("%d\n", dfs(1, strlen(s+1))); } return 0; }