博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HDU 1141---Brackets Sequence(区间DP)
阅读量:4841 次
发布时间:2019-06-11

本文共 2195 字,大约阅读时间需要 7 分钟。

 题目链接

 

Description

Let us define a regular brackets sequence in the following way: 
1. Empty sequence is a regular sequence. 
2. If S is a regular sequence, then (S) and [S] are both regular sequences. 
3. If A and B are regular sequences, then AB is a regular sequence. 
For example, all of the following sequences of characters are regular brackets sequences: 
(), [], (()), ([]), ()[], ()[()] 
And all of the following character sequences are not: 
(, [, ), )(, ([)], ([(] 
Some sequence of characters '(', ')', '[', and ']' is given. You are to find the shortest possible regular brackets sequence, that contains the given character sequence as a subsequence. Here, a string a1 a2 ... an is called a subsequence of the string b1 b2 ... bm, if there exist such indices 1 = i1 < i2 < ... < in = m, that aj = bij for all 1 = j = n.

Input

The input file contains at most 100 brackets (characters '(', ')', '[' and ']') that are situated on a single line without any other characters among them.

Output

Write to the output file a single line that contains some regular brackets sequence that has the minimal possible length and contains the given sequence as a subsequence.

Sample Input

([(]

Sample Output

()[()]

Source

 
 
题意:给了一个括号序列(只有"("  ")"  "["  "]") 现在让添加括号,使括号序列变得匹配,要求添加最少的括号,输出这个匹配的括号序列;
 
思路:区间DP,dp[i][j]表示区间i~j匹配添加括号后区间最小长度,dp[i][j]=dp[i][k]+dp[k+1][j] ,注意当s[i]=='('&&s[j]==')' || s[i]=='['&&s[j]==']' 时,特判一下dp[i][j]=min(dp[i][j],dp[i+1][j-1]+2);  这样可以找出匹配后的序列最小长度,但是题目要求输出匹配的序列,那么可以在定义一个数组v[i][j] 标记i~j区间的断开位置,如果s[i]=='('&&s[j]==')' || s[i]=='['&&s[j]==']' 时 v[i][j]==-1, 然后在递归调用输出即可;
 
代码如下:
#include 
#include
#include
#include
#include
using namespace std;const int inf=0x3f3f3f3f;char s[105];int v[105][105];int dp[105][105];void print(int l,int r){ if(r
dp[i][k]+dp[k+1][i+l]) { dp[i][i+l]=dp[i][k]+dp[k+1][i+l]; v[i][i+l]=k; } } if(s[i]=='('&&s[i+l]==')'||s[i]=='['&&s[i+l]==']') { if(dp[i][i+l]>dp[i+1][i+l-1]+2) { dp[i][i+l]=dp[i+1][i+l-1]+2; v[i][i+l]=-1; } } } } print(0,len-1); printf("\n"); return 0;}

 

转载于:https://www.cnblogs.com/chen9510/p/5849467.html

你可能感兴趣的文章
POJ 1611 The Suspects
查看>>
每日站立会议——Day5
查看>>
构建执法第二章读后感
查看>>
【收藏】win7打开word每次提示配置解决办法
查看>>
POJ1143 Number Game(DP)
查看>>
等价类划分例子中的些许添加
查看>>
《剑指offer》---斐波那契数列
查看>>
Vue自定义指令(directive)
查看>>
webservice使用注解修改WSDL内容
查看>>
SystemView 破解方法记录
查看>>
【vijos1642】班长的任务
查看>>
JavaScript入门基础(四)
查看>>
校内的hu测(10.5)
查看>>
Windows Forms高级界面组件-使用对话框
查看>>
Objective-C中的深拷贝和浅拷贝
查看>>
超实用的JQuery小技巧
查看>>
设计模式——单例模式 (C++实现)
查看>>
UML和模式应用学习笔记(6)——系统顺序图、系统操作和层
查看>>
Android -- startActivityForResult和setResult
查看>>
1019 General Palindromic Number (20 分)
查看>>