Brackets Sequence
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
() [()]
Interval DP, focus on output
# Include <iostream> # include <cstdio> # include <cstring> using namespace STD; # define max (A, B) (a)> (B )? (A) :( B) # define INF 0x7fffffff # define n 110 char s [N]; int ss [N] [N]; // ss [I] [J] = K, the number of parentheses separated from K by I to J is at least int DP [N] [N]; // DP [I] [J] is in ~ Maximum number of parentheses in the J interval int judge (char C1, char C2) {If (C1 = '(' & C2 = ') return 1; if (C1 = '[' & C2 = ']') return 1; return 0;} void print (int I, Int J) {if (I> J) return; else if (I = J) {If (s [I] = '(' | s [I] = ') cout <"() "; else cout <" [] ";} else {If (ss [I] [J] =-1) {cout <s [I]; print (I + 1, J-1); cout <s [J];} else {print (I, ss [I] [J]); print (ss [I] [J] + 1, J) ;}} int main () {int N, I, J, K, Len; gets (S + 1); n = strlen (S + 1); for (I = 1; I <= N; I ++) {DP [I] [I] = 1 ;}for (LEN = 2; Len <= N; Len ++) {for (I = 1; I <= N-len + 1; I ++) {J = I + len-1; DP [I] [J] = inf; For (k = I; k <J; k ++) {If (DP [I] [J]> DP [I] [k] + dp [k + 1] [J]) {ss [I] [J] = K; DP [I] [J] = DP [I] [k] + dp [k + 1] [J];} if (Judge (s [I], s [J]) & DP [I] [J]> DP [I + 1] [J-1]) {ss [I] [J] =-1; DP [I] [J] = DP [I + 1] [J-1] ;}} // cout <DP [1] [N] <Endl; print (1, N); printf ("\ n"); Return 0 ;}
Interval DP [poj 1141] brackets Sequence