题目如下:
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.
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
()[()]
解答:
用char *str 记录符号,Int * *state 记录符号数,state[i][j]表示str[i]……str[j]补全括号之后的括号数;
用string * *ans表示补全括号之后的串,ans[i][j]表示str[i]……str[j]补全括号之后的括号串
主要注意两句话:
第一句:If A and B are regular sequences, then AB is a regular sequence
那我们可以得出如下状态转移方程:
state[i][j]=min(state[i][k]+state[k+1][j]) (i<=k<=j)
ans[i][j]=ans[i][k]+ans[k+1][j]
第二句:If S is a regular sequence, then (S) and [S] are both regular sequences.
我们可以得到:
state[i][j]=min(state[i][j],state[i+1][j-1]+2) if(match(str[i],str[j]))
ans[i][j]=str[i]+ans[i+1][j-1]+str[j]
值得注意的是初始化数据:
state[i][i]=2
state[i][j]=0 if(i>j);
以下是代码:
代码1是用了纯DP的方式
代码2用了备忘录。但是两者的基本思想都是一样的。
代码1:
代码2: