poj2955(区间dp)

题意:

给出括号,问括号匹配的最大个数。

题解:

状态方程:

if (match(i, j))  dp[i][j] = dp[i + 1][j - 1] + 2;//这是精髓
dp[i][j] = max(dp[i][k] + dp[k + 1][j], dp[i][j]);

#include<iostream>
#include<math.h>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<vector>
using namespace std;
//typedef __int64 lld;
#define oo 0x3f3f3f3f
#define Mod 1000000007
#define maxn 105
int dp[maxn][maxn];
char str[maxn];

bool match(int i, int j)
{
	if (str[i] == '('&&str[j] == ')')
		return true;
	if (str[i] == '['&&str[j] == ']')
		return true;
	return false;
}

int main()
{
	int n;
	while (scanf("%s", str + 1) && str[1] != 'e')
	{
		n = strlen(str + 1);
		memset(dp, 0, sizeof dp);
		for (int i = 1; i <= n; i++)
		{
			if (match(i, i + 1))
				dp[i][i + 1] = 2;
		}
		for (int L = 3; L <= n; L++)
            for (int i = 1; i <= n; i++)
            {
                int j = i + L - 1;
                if (j <= n)
                {
                    if (match(i, j))
                        dp[i][j] = dp[i + 1][j - 1] + 2;
                    for (int k = i; k < j; k++)
                        dp[i][j] = max(dp[i][k] + dp[k + 1][j], dp[i][j]);
                }
            }
		printf("%d\n", dp[1][n]);
	}
	return 0;
}


你可能感兴趣的:(dp,poj)