题目链接: http://poj.org/problem?id=2955
题目大意:括号匹配。对称的括号匹配数量+2。问最大匹配数。
解题思路:
看起来像个区间问题。
DP边界:无。区间间隔为0时,默认为memset为0即可。
对于dp[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][j]),合并两个区间的结果。
#include "cstdio"
#include "string"
#include "cstring"
#include "iostream"
using namespace std;
bool check(char a,int b)
{
if(a=='('&&b==')') return true;
else if(a=='['&&b==']') return true;
else return false;
}
int dp[][];
int main()
{
//freopen("in.txt","r",stdin);
string str;
while(cin>>str&&str!="end")
{
int n=str.size();
for(int p=;p<n;p++)
{
for(int i=;i<n-p;i++)
{
int j=i+p;
if(check(str[i],str[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-]);
memset(dp,,sizeof(dp));
}
}