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 = + ;
const int MOD = 1e9 + ;
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 + )){
if(strcmp(s + , "end") == ) break;
memset(dp, , sizeof(dp));
int n = strlen(s + );
for(int len = ; len <= n; len++){
for(int i = ; i + len - <= n; i++){
int j = i + len - ;
if(ok(i, j)){
dp[i][j] = dp[i + ][j - ] + ;
}
for(int k = i; k < j; k++){
dp[i][j] = max(dp[i][j], dp[i][k] + dp[k + ][j]);
}
}
}
printf("%d\n", dp[][n]);
}
return ;
}
上一篇:编程从入门到提高,然后放弃再跑路(Java)


下一篇:第九十九天上课 PHP TP框架 数据库查询和增加