首页 > 代码库 > POJ 2955 Brackets 区间DP

POJ 2955 Brackets 区间DP

题目来源:POJ 2955 Brackets

题意:最大括号匹配

思路:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
using namespace std;
const int maxn = 210;
int dp[maxn][maxn];
char a[maxn];
int b[maxn];
int dfs(int l, int r)
{
	if(l > r)
		return 0;
	if(dp[l][r] != -1)
		return dp[l][r];
	
	if(l+1 == r)
	{
		if(b[l] < 2 && b[l]+b[r] == 3)
			dp[l][r] = 1;
		else
			dp[l][r] = 0;
		return dp[l][r];
	}
	if(l == r)
	{
		dp[l][r] = 0;
		return dp[l][r];
	}
	dp[l][r] = 0;
	if(b[l] < 2 && b[l] + b[r] == 3)
	{
		dp[l][r] = max(dp[l][r], dfs(l+1, r-1)+1);
	}
	else 
	{
		dp[l][r] = max(dp[l][r], dfs(l+1, r-1));
	}
	for(int i = l; i <= r; i++)
	{
		dp[l][r] = max(dp[l][r], dfs(l, i)+dfs(i+1, r));
	}
	return dp[l][r];
}
int main()
{
	while(gets(a) && (strcmp(a, "end")))
	{
		memset(dp, -1, sizeof(dp));
		for(int i = 0; a[i]; i++)
		{
			if(a[i] == '(')
				b[i] = 0;
			else if(a[i] == ')')
				b[i] = 3;
			else if(a[i] == '[')
				b[i] = 1;
			else if(a[i] == ']')
				b[i] = 2;
		}
		printf("%d\n", dfs(0, strlen(a)-1)*2);
	}
	return 0;
}