第十二周作业-选做1

题目描述:
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.
sample:
input:
((()))
()()()
([]])
)[)(
([][][)
end
output:
6
6
4
0
6
题目分析:
本题是动态规划问题,这样我们就需要遍历所有的子串求出最大值,对于所有的子串而言,子串的合法序列子串的转移方程就是整体的合法子串和拆分成两部分的子串中的合法序列两个哪一个。

d[l][r]=max(d[l][r],d[l][k]+d[k+1][r]);

如果发现两个端点的括号也符合要求,那么就把他俩加进来,然后比较加进来这一组和其余的谁大谁小。

d[l][r]=max(d[l][r],d[l+1][r-1]+2);

遍历求所有的子串就是先按照长度从2到n所有可能长度的子串内,对左端点进行一次遍历,每次遍历的右端就是左端+长度-1,然后对子串的长度进行状态转移就可以了。

		for(int i=2;i<=n;i++)
		{
			for(int l=0;l<=n-i;l++)
			{
				int r=l+i-1;
				d[l][r]=-114514893;
				for(int k=l;k<=r;k++)

最终的结果就是整个字符串的合法子串的大小了,就是从0到n-1(因为起始位置从0开始)

cout<<d[0][n-1]<<endl;

代码如下:

#include<iostream>
#include<cstring>
using namespace std;
int d[110][110];
int main()
{
	string str;
	while(cin>>str)
	{
		if(str=="end")
		{
			break;
		}
		memset(d,0,sizeof(d));
		int n=str.size();
		for(int i=2;i<=n;i++)
		{
			for(int l=0;l<=n-i;l++)
			{
				int r=l+i-1;
				d[l][r]=-114514893;
				for(int k=l;k<=r;k++)
				{
					d[l][r]=max(d[l][r],d[l][k]+d[k+1][r]);
				}
				if((str[l]=='('&&str[r]==')')||(str[l]=='['&&str[r]==']'))
				{
					d[l][r]=max(d[l][r],d[l+1][r-1]+2);
				}
			}
		}
		cout<<d[0][n-1]<<endl;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值