括号匹配

poj 2955

http://poj.org/problem?id=2955

题目大意:找到数量最多的完全匹配的括号        ‘[’与‘]'匹配,'('与')'匹配

区间dp

定义dp[i][j]为从i到j数量最多的完全匹配的括号

当 str[i]=='[' && str[j]==']' 或 str[i]=='(' && str[j]==')' 时  dp[i][j]=dp[i+1][j-1]+2;

代码

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=110;
char str[N]; 
int dp[N][N];
int main()
{
    while(~scanf("%s",str+1))
    {
        if(str[1]=='e') break;
        memset(dp,0,sizeof(dp));
        int ans=-1;
        int len=strlen(str+1);
        for(int v=1;v<=len;v++)
            for(int i=1;i+v-1<=len;i++)
            {
                int j=i+v-1;
                if((str[i]=='['&&str[j]==']')||(str[i]=='('&&str[j]==')'))
                    dp[i][j]=dp[i+1][j-1]+2;
                for(int k=i;k<j;k++)
                    dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]);
                ans=max(ans,dp[i][j]);
            }
        printf("%d
",ans);
    }
    return 0;
 } 

变式:括号匹配2

只需要括号总数减去最大完全匹配括号数即可

代码

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=110;
char str[N]; 
int dp[N][N];
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%s",str+1);
        memset(dp,0,sizeof(dp));
        int ans=-1;
        int len=strlen(str+1);
        for(int v=1;v<=len;v++)
            for(int i=1;i+v-1<=len;i++)
            {
                int j=i+v-1;
                if((str[i]=='['&&str[j]==']')||(str[i]=='('&&str[j]==')'))
                    dp[i][j]=dp[i+1][j-1]+2;
                for(int k=i;k<j;k++)
                    dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]);
                ans=max(ans,dp[i][j]);
            }
        printf("%d
",len-ans);
    }
    return 0;
 } 
原文地址:https://www.cnblogs.com/greengenius/p/9231825.html