[状态压缩]---Brackets
来源:互联网 发布:java nio和io的区别 编辑:程序博客网 时间:2024/06/03 05:14
标签: ACM
题目:
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 [([])].
Input
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.
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
解题思路:
两种满足的条件
第一种如果两括号匹配则等于中间的匹配+2
第二种区间的匹配等于区间中的相邻区间匹配之和
将2个匹配到最大个数匹配遍历一遍最后就是答案
还是直接看AC代码容易理解些吧…….
#include <iostream>#include <string.h>using namespace std;int dp[105][105]; //表示从i到j字符串的最大匹配bool match(char a ,char b){ return ((a=='('&&b==')')||(a=='['&&b==']'));}int max(int a,int b){ return (a>b?a:b);}int main(){ string s; int len,i,j,k,t; while(cin>>s) { memset(dp,0,sizeof(dp)); if(s=="end") break; len=s.size(); for(i=1;i<len;i++) //匹配i+1长度的字符串 for(j=0,k=i;k<len;j++,k++) { if(match(s[j],s[k])) //寻找最大包含匹配 dp[j][k]=dp[j+1][k-1]+2; //如果j到k匹配,则等于两者中间的匹配度加2 for(t=j;t<k;t++) //寻找最大相邻匹配 dp[j][k]=max(dp[j][k],dp[j][t]+dp[t+1][k]); } cout<<dp[0][len-1]<<endl; } return 0;}
- [状态压缩]---Brackets
- 状态压缩
- 状态压缩
- 状态压缩
- 状态压缩
- 状态压缩
- 状态压缩
- 状态压缩
- 状态压缩
- 状态压缩
- 状态压缩
- 状态压缩
- 状态压缩
- 状态压缩
- 状态压缩
- 状态压缩
- Brackets
- Brackets
- 13. Roman to Integer(12/6/2017)
- 2017 SCNU软件学院 蓝桥杯预选赛 题解(非官方)
- 欢迎使用CSDN-markdown编辑器
- 状态压缩--方格取数
- 【状态压缩】---状态压缩dp第一题
- [状态压缩]---Brackets
- [状态压缩]---区间dp第一题
- python一周速成学习笔记
- python实战--数据结构二叉树
- 【线段树】-敌兵布阵 --单节点更新
- [全排列]--A Number Puzzle
- Maven项目下载sqljdbc4-4.0.jar失败
- 学习计算机的书
- MySQL的语句执行顺序