POJ2955 (括号匹配)[区间DP] 发表于 2018-08-20 | 更新于 2020-07-30 | | 阅读次数: 这题是区间DP,状态转移方程d[l][r]=d[l-1][r-1]+2, s[l]与s[r]可以匹配, d[l][r]=max{d[l][k-1]+d[k][r]}, l<k<=r 12345678910111213141516171819202122232425262728#include <cstdio>#include <algorithm>#include <cstring>using namespace std;const int maxn=109;int dp[maxn][maxn];char s[maxn];bool match(char a,char b) { if(a=='(' && b==')') return true; if(a=='[' && b==']') return true; return false;}int main() { while(~scanf("%s",s)) { if(strcmp(s,"end")==0) break; int n=strlen(s); memset(dp,0,sizeof(dp)); for(int len=2;len<=n;len++) { for(int l=1;l+len-1<=n;l++) { int r=l+len-1; if(match(s[l-1],s[r-1])) dp[l][r]=dp[l+1][r-1]+2; for(int k=l+1;k<=r;k++) dp[l][r]=max(dp[l][r],dp[l][k-1]+dp[k][r]); } } printf("%d\n",dp[1][n]); }}