POJ 2955 Brackets(区间DP)题解

题意:问最多有几个括号匹配

思路:用dp[i][j]表示i到j最多匹配,若i和j构成匹配,那么dp[i][j] = dp[i + 1][j - 1] + 2,剩下情况dp[i][j] = max(dp[i][j], dp[i][k] + dp[k + 1][j])

代码:

#include<set>
#include<map>
#include<cmath>
#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
typedef long long ll;
using namespace std;
const int maxn = 100 + 10;
const int MOD = 1e9 + 7;
const int INF = 0x3f3f3f3f;
int dp[maxn][maxn];
char s[maxn];
bool ok(int i, int j){
    if(s[i] == '(' && s[j] == ')') return true;
    if(s[i] == '[' && s[j] == ']') return true;
    return false;
}
int main(){
    while(~scanf("%s", s + 1)){
        if(strcmp(s + 1, "end") == 0) break;
        memset(dp, 0, sizeof(dp));
        int n = strlen(s + 1);
        for(int len = 2; len <= n; len++){
            for(int i = 1; i + len - 1 <= n; i++){
                int j = i + len - 1;
                if(ok(i, j)){
                    dp[i][j] = dp[i + 1][j - 1] + 2;
                }
                for(int k = i; k < j; k++){
                    dp[i][j] = max(dp[i][j], dp[i][k] + dp[k + 1][j]);
                }
            }
        }
        printf("%d\n", dp[1][n]);
    }
    return 0;
}

 

posted @ 2019-01-24 22:05  KirinSB  阅读(138)  评论(0编辑  收藏  举报