Description
Let us define a regular brackets sequence in the following by:
- Empty sequence is a regular sequence.
- If S is a regular sequence, then (s) and [s] are both regular sequences.
- If A and B are regular sequences, then AB is A regular sequence.
For example, all of the following sequences of characters is regular brackets sequences:(),[],(()),([]),()[],()[()]And all of the following character sequences is not:(,[,),)(,([)],([(]Some sequence of characters ' (', ') ', ' [', and '] ' is given. You is to find the shortest possible regular brackets sequence, that contains the given character sequence as a Subsequen Ce. Here, a string a 1a 2...a n is called a subsequence of the string B 1b 2...b m, if there exist such indices 1≤i 1 < i 2 < ... < I n≤m, that's a j=b ij for all 1≤j≤n.
Input
The input contains at most of brackets (characters ' (', ') ', ' [' and '] ') that is situated on a single line without any Other characters among them.
Output
Write A single line This contains some regular brackets sequence that have the minimal possible length and contains the GIV En sequence as a subsequence.
Sample Input
To match the fewest parentheses and output
Define DP[I][J] represents the minimum required matching brackets from I to J, define POS[I][J] to indicate whether the parentheses match from I to J
State transition equation Dp[x][y] = min (Dp[x][y],dp[x][i]+dp[i+1][y])
Jiege Code
#include <cstdio> #include <cstring> #include <algorithm>using namespace Std;int dp[110][110];int Pos [110] [110];char s[110];const int inf = 0x3f3f3f3f;void dfs (int x,int y) {if (Dp[x][y]! =-1) return; if (x > Y) {dp[x][y] = 0; return; } if (x = = y) {dp[x][y] = 1; return; } Dp[x][y] = inf; if ((s[x] = = ' (' && s[y] = = ') ') | | (S[x] = = ' [' && s[y] = = '] ')) {Pos[x][y] =-1; DFS (X+1,Y-1); Dp[x][y] = dp[x+1][y-1]; } for (int i = x; i < y; i++) {DFS (x,i); DFS (I+1,Y); if (Dp[x][i] + Dp[i+1][y] < Dp[x][y]) {dp[x][y] = Dp[x][i] + dp[i+1][y]; Pos[x][y] = i; }}}void print (int x,int y) {if (x > Y) return; if (x = = y) {if (s[x] = = ' (' | | s[x] = = ') ') printf ("()"); else printf ("[]"); return; } if (pos[x][y] = = 1) {printf ("%c", s[x]); Print (x+1,y-1); printf ("%c ", S[y]); } else {print (x,pos[x][y]); Print (pos[x][y]+1,y); }}int Main () {scanf ("%s", s+1); int n = strlen (s+1); Memset (Dp,-1,sizeof (DP)); DFS (1,N); Print (1,n); printf ("\ n"); return 0;}
ural1183--dfs+ Retrospective--brackets Sequence