• 括号匹配


    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;
     } 
  • 相关阅读:
    Cx的治疗
    [HDU2222] Keywords Search
    楼房
    [51Nod1089] 最长回文子串 V2(Manacher算法)
    [洛谷P3375] 【模板】KMP字符串匹配
    [codeVS1204] 寻找子串位置
    [洛谷P1114] “非常男女”计划
    [BZOJ2132] 圈地计划
    [COGS311] Redundant Paths
    [COGS309] [USACO 3.2] 香甜的黄油
  • 原文地址:https://www.cnblogs.com/greengenius/p/9231825.html
Copyright © 2020-2023  润新知