当前位置: 代码迷 >> 综合 >> poj 2955 Brackets(区间DP,经典问题)求有规律的括号的最大长度
  详细解决方案

poj 2955 Brackets(区间DP,经典问题)求有规律的括号的最大长度

热度:21   发布时间:2024-01-13 20:34:25.0

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

2、题目大意

给出一个只包含()[]的字符序列,求出该字符序列中有规律的符号序列的最长长度

有规律的序列要求如下:

  • the empty sequence is a regular brackets sequence,
  • if s is a regular brackets sequence, then (s) and [s] are regular brackets sequences, and
  • if a and b are regular brackets sequences, thenab is a regular brackets sequence.
  • no other sequence is a regular brackets sequence

dp[i][j]表示i到j区间有规律字符串的最大长度

dp[i][j]=max(dp[i][j],dp[i][k]+dp[k][j])其中i=<k<j

3、AC代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define N 105
char str[N];
int dp[N][N];
int check(char a,char b)
{if((a=='(' && b==')') || (a=='[' && b==']'))return 1;return 0;
}
int main()
{while(scanf("%s",str)!=EOF){if(strcmp(str,"end")==0)break;int len=strlen(str);memset(dp,0,sizeof(dp));for(int i=0;i<len-1;i++){if(check(str[i],str[i+1]))dp[i][i+1]=2;}for(int i=3;i<=len;i++){for(int j=0;i+j-1<len;j++){//dp[j][i+j-1]=0;if(check(str[j],str[i+j-1]))dp[j][i+j-1]=dp[j+1][i+j-2]+2;for(int k=j;k<i+j-1;k++){dp[j][i+j-1]=max(dp[j][i+j-1],dp[j][k]+dp[k][i+j-1]);}//printf("*%d %d %d\n",j,j+i-1,dp[j][i+j-1]);}}printf("%d\n",dp[0][len-1]);}return 0;
}


 

  相关解决方案