标签:
对应NYOJ题目:点击打开链接
4 [] ([])[] ((] ([)]
0 0 3 2
思路:区间DP。dp[i][j]表示第i个位置到第j个位置的最多匹配数(是2的倍数)。那串的长度 - dp[0][n-1] 就是答案。
先把相邻的匹配括号初始化为dp[i][i+1] = 2;如果str[i] 与 str[j] 匹配,则dp[i][j] = dp[i+1][j-1] + 2;之后有转移方程:dp[i][j] = max{dp[i][j], dp[i][k] + dp[k+1][j]}(i <= k <j);
#include <stdio.h> #include <stdlib.h> #include <string.h> #define M 110 #define MAX(x, y) ((x) > (y) ? (x) : (y)) char str[M]; int dp[M][M]; bool Check(char a, char b) { if(a == '[' && b == ']') return 1; if(a == '(' && b == ')') return 1; return 0; } int main() { //freopen("in.txt", "r", stdin); int T; int l, i, j, k, len; scanf("%d", &T); while(T--) { scanf("%s", str); memset(dp, 0, sizeof(dp)); len = strlen(str); for(i=0; i+1<len; i++) if(Check(str[i], str[i+1])) dp[i][i+1] = 2; for(l=2; l<=len; l++){ for(i=0; i+l-1<len; i++){ j = i + l - 1; if(Check(str[i], str[j])) dp[i][j] = dp[i+1][j-1] + 2; for(k=i; k+1<=j; k++){ dp[i][j] = MAX(dp[i][j], dp[i][k] + dp[k+1][j]); } } } printf("%d\n", len - dp[0][len-1]); } return 0; }
标签:
原文地址:http://blog.csdn.net/u013351484/article/details/44758769