Link:http://poj.org/problem?id=2955
Brackets
Description We give the following inductive definition of a “regular brackets” sequence:
For instance, all of the following character sequences are regular brackets sequences:
while the following character sequences are not:
Given a brackets sequence of characters a1a2 … an, your goal is to find the length of the longest regular brackets sequence that is a subsequence of s. That is, you wish to find the largest m such that for indices i1, i2, …, im where 1 ≤ i1 < i2 < … < im ≤ n, ai1ai2 … aim is a regular brackets sequence. Given the initial sequence Input The input test file will contain multiple test cases. Each input test case consists of a single line containing only the characters Output For each input case, the program should print the length of the longest possible regular brackets subsequence on a single line. Sample Input ((())) ()()() ([]]) )[)( ([][][) end Sample Output 6 6 4 0 6 Source |
题意:给出一段由括号组成的字符串,求该字符串最大的匹配长度。
编程思想:区间DP。
设dp[i][j]表示区间i到j最大的括号匹配长度,则从后往前推,当匹配到第i个括号时,先假设第i个括号后面的括号没有能与它匹配的,那么状态转移为dp[i][j]=dp[i+1][j];然后从枚举区间i+1到j,若有与括号i匹配的,则求能匹配的最大值,若全部都没有与之匹配的,那么dp[i][j]=dp[i+1][j];所以当有与括号i匹配的括号k时,状态转移为dp[i][j]=max(dp[i][j],dp[i+1][k]+dp[k][j]+2);其中dp[i+1][k]+dp[k][j]+2中的2就是加上括号k与括号i匹配的长度。
AC code:
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<cstring>
#include<cmath>
#include<vector>
using namespace std;
char str[111];
int dp[111][111];//dp[i][j]表示区间i到j最大的括号匹配数
int main()
{
//freopen("D:\\in.txt","r",stdin);
int i,j,k,len;
while(scanf("%s",str+1)!=EOF)
{
if(strcmp(str+1,"end")==0)
break;
len=strlen(str+1);
memset(dp,0,sizeof(dp));
for(i=len-1;i>=1;i--)//枚举区间起点
{
for(j=i+1;j<=len;j++)//枚举区间终点
{
dp[i][j]=dp[i+1][j];
if(str[i]=='('||str[i]=='[')
{
for(k=i+1;k<=j;k++)
{
if(str[k]==')'&&str[i]=='(')
dp[i][j]=max(dp[i][j],dp[i+1][k-1]+dp[k][j]+2);
if(str[k]==']'&&str[i]=='[')
dp[i][j]=max(dp[i][j],dp[i+1][k-1]+dp[k][j]+2);
}
}
}
}
printf("%d\n",dp[1][len]);
}
return 0;
}