区间dp POJ2955 Bracket

题目链接:

http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=23652

题意:

给定一些括号,按照题目取法问最多有多少匹配的括号

思路:

区间dp。主要是下标处理,原来还考虑了k比j小的情况怎么处理,然后发现所有值都初始化为0,所以就没有必要多加判断了。

源码:

#include <cstdio>

#include <cstring>

#include <string>

#include <iostream>

#include <algorithm>

#include <cmath>

using namespace std;

#define gmax(a,b) a>b?a:b

const int MAXN = 100+5;

char data[MAXN];

int dp[MAXN][MAXN];

int main()

{

   while(scanf("%s",data)!=EOF &&strcmp(data,"end")){

       memset(dp,0,sizeof(dp));

       int len = strlen(data);

       for(int i=1; i<len; i++){

           for(int j=0; j+i<len; j++){

                for(int k=j+1; k<=j+i; k++){

                    if((data[j]=='[' && data[k]==']')|| (data[j]=='(' && data[k]==')')){

//                        printf("j = %d,k =%d\n",j,k);

//                        printf("data[j] =%c,data[k] = %c\n",data[j],data[k]);

                        dp[j][j+i] = gmax(dp[j][j+i],dp[j+1][k-1]+dp[k+1][j+i]+2);

                    }

                    else

                        dp[j][j+i] =gmax(dp[j][j+i],dp[j+1][k-1]+dp[k][j+i]);

                }

           }

       }

//       for(int i=0; i<len; i++){

//            for(int j=0; j<len; j++)

//                printf("%d",dp[i][j]);

//            printf("\n");

//       }

       printf("%d\n",dp[0][len-1]);

    }

   return 0;

}

你可能感兴趣的:(区间dp POJ2955 Bracket)