POJ Brackets (区间dp)

题目链接:http://poj.org/problem?id=2955


题意:给出一串括号,‘(’与‘)’匹配‘ [ ’与‘ ] ’匹配,问最多有几个匹配得括号


思路:区间dp,刚做的时候想到了之前某道题的思路:如果s[i]与s[k]匹配dp=min(dp[i][j],dp[i+1][k-1]+dp[k+1][j-1])然后特判k=j以及k=i+1的情况。后来看了下这道题很久之前居然做过……直接更新区间最大值就可以了


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;

char s[130];
int dp[130][130];

int main()
{
    while (scanf("%s",&s)!=EOF)
    {
        if (s[0]=='e') break;

        int len=strlen(s);
        memset(dp,0,sizeof(dp));
        for (int i=0;i<len-1;i++)
        {
            if (s[i]=='(' && s[i+1]==')' || s[i]=='[' && s[i+1]==']')
                dp[i][i+1]=2;
        }

        for (int l=3;l<=len;l++)
        {
            for (int i=0;i+l-1<len;i++)
            {
                int j=i+l-1;
                dp[i][j]=max(dp[i][j],dp[i+1][j]);
                if (s[i]=='(' && s[i+1]==')' || s[i]=='[' && s[i+1]==']')
                    dp[i][j]=max(dp[i][j],dp[i+2][j]+2);

                if (s[i]=='(' && s[j]==')' || s[i]=='[' && s[j]==']')
                    dp[i][j]=max(dp[i][j],dp[i+1][j-1]+2);

                for (int k=i+2;k<j;k++)
                {
                    if (s[i]=='(' && s[k]==')' || s[i]=='[' && s[k]==']')
                    {
                        dp[i][j]=max(dp[i][j],dp[i+1][k-1]+dp[k+1][j]+2);
                    }
                }
            }
        }
        printf("%d\n",dp[0][len-1]);
    }
}

以前的代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
char s[130];
int dp[130][130];

int check(int i,int j)
{
    if (s[i]=='(' && s[j]==')') return 1;
    if (s[i]=='[' && s[j]==']') return 1;
    return 0;
}


int main()
{
    while (scanf("%s",&s)!=EOF)
    {
        if (s[0]=='e') break;
        int l=strlen(s);
        memset(dp,0,sizeof(dp));
        for (int k=1;k<l;k++)
        {
            for (int i=0;i+k<l;i++)
            {
                int j=k+i;
                if (check(i,j)) dp[i][j]=max(dp[i][j],dp[i+1][j-1]+2);
                else dp[i][j]=max(dp[i+1][j],dp[i][j-1]);

                for (int ki=1;ki<k;ki++)
                 dp[i][j]=max(dp[i][j],dp[i][i+ki]+dp[ki+1+i][j]);
            }
        }
        printf("%d\n",dp[0][l-1]);
    }
}

                                                                                                    

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