题目链接:
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 Sample Output Source |
题目大意:
就是区间dp
This is the code
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<iomanip>
#include<list>
#include<map>
#include<queue>
#include<sstream>
#include<stack>
#include<string>
#include<set>
#include<vector>
using namespace std;
#define PI acos(-1.0)
#define EPS 1e-8
#define MOD 1e9+7
#define LL long long
#define ULL unsigned long long //1844674407370955161
#define INT_INF 0x7f7f7f7f //2139062143
#define LL_INF 0x7f7f7f7f7f7f7f7f //9187201950435737471
const int dr[]={0, 0, -1, 1, -1, -1, 1, 1};
const int dc[]={-1, 1, 0, 0, -1, 1, -1, 1};
// ios::sync_with_stdio(false);
// 那么cin, 就不能跟C的 scanf,sscanf, getchar, fgets之类的一起使用了。
char s[105];
int dp[105][105];
bool check(char x,int y)
{
if( (x=='(' && y==')') || (x=='[' && y==']') )
return true;
return false;
}
int main()
{
while(~scanf(" %s",s))
{
if(s[0]=='e')
break;
int len=strlen(s);
memset(dp,0,sizeof(dp));
for(int l=2;l<=len;++l)//区间长度
{
for(int i=0;i+l-1<len;++i)//区间起始点
{
int j=i+l-1;//表示区间终点
if(check(s[i],s[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]);
}
}
printf("%d\n",dp[0][len-1]);
}
return 0;
}