@xunuo
2017-01-16T14:18:29.000000Z
字数 2018
阅读 1199
Time limit 1000 ms Memory limit 65536 kB
区间DP
来源:
vjudge: D-Brackets
poj: poj 2955 Brackets
We give the following inductive definition of a “regular brackets” sequence:
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, then ab is a regular brackets sequence.
no other sequence is 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 ([([]])], the longest regular brackets subsequence is [([])].
The input test file will contain multiple test cases. Each input test case consists of a single line containing only the characters (, ), [, and ]; each input test will have length between 1 and 100, inclusive. The end-of-file is marked by a line containing the word “end” and should not be processed.
For each input case, the program should print the length of the longest possible regular brackets subsequence on a single line.
((()))
()()()
([]])
)[)(
([][][)
end
6
6
4
0
6
题意:
给出一个只有'(' ')' '[' ']' 的字符串,要你求出完整的'()' 和'[]' 总共有多少个
解题思路
由多方可知...这是一个很典型的区间DP,用dp[i][j]表示[i,j]区间内符合条件的括号的个数,其状态转移方程为:
dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j])///k为i与j之间的状态
而当s[i],s[j]满足组成一个完整的括号时,
dp[i][j]=dp[i+1][j-1]+2;
完整代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int main()
{
char s[110];
int dp[110][110];
while(scanf("%s",s)!=EOF)
{
memset(dp,0,sizeof(dp));
if(s[0]=='e')
break;
int len=strlen(s);
for(int i=0;i<len;i++)
{
if((s[i]=='('&&s[i+1]==')')||(s[i]=='['&&s[i+1]==']'))
dp[i][i+1]=2;
}
for(int l=2;l<len;l++)
for(int i=0;i<len-l;i++)
{
int j=i+l;
if((s[i]=='('&&s[j]==')')||(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;
}