POJ_2955_Brackets
来源:互联网 发布:java驻场开发 编辑:程序博客网 时间:2024/06/05 06:46
Description
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
66406
Source
两种括号的匹配问题,这个问题并不能顺序解决
因为两种括号存在交叉的情形,
而且有些情况并不能知道优先匹配哪种括号
这个题目注意分段 dp[st][en]=max{dp[st][mi]+dp[mi+1][en]}
或者当st与mi匹配时转移到dp[st][en]=max{dp[st+1][mi-1]+2+dp[mi+1][en]}
#include <iostream>#include <stdio.h>#include <string.h>using namespace std;const int M=105;const int IN=1000;char pa[M];int dp[M][M];int main(){ int len; while(scanf("%s",pa+1)!=EOF) { if(pa[1]=='e') break; memset(dp,0,sizeof(dp)); len=strlen(pa+1); //求长度这里注意下开始的位置 for(int l=2;l<=len;l++) for(int st=1;st<=len-l+1;st++) { int co=0; for(int mi=st;mi<=st+l-1;mi++) { if((pa[st]=='('&&pa[mi]==')')||(pa[st]=='['&&pa[mi]==']')) co=max(co,dp[st+1][mi-1]+2+dp[mi+1][st+l-1]); else co=max(co,dp[st][mi]+dp[mi+1][st+l-1]); //cout<<st<<" "<<l<<" "<<mi<<" "<<co<<endl; } dp[st][st+l-1]=co; } printf("%d\n",dp[1][len]); } return 0;}
- POJ_2955_Brackets
- C++对象模型——Data 语意学(第三章)
- windows学习笔记二 --滚动条的绘制
- BFS-POJ-3126-Prime Path
- 树:深度优先搜索、广度优先搜索、背包问题
- 4步win7下简单FTP服务器搭建(试验成功)
- POJ_2955_Brackets
- 达内学习日志 DAY02(续):变量与java的基本数据类型(int,long,float,double,char,boolean)
- CSS基础-33面向对象的 CSS 课程概要,要反复看视频
- 重建二叉树
- UICollectionView学习
- Android笔记——Activity中的数据传递案例(用户注册)
- 28个不得不看的经典编程算法!!
- iOS获取键盘高度的方法
- 程序随笔:汉诺塔