Question Link
Question: Give You A string composed of parentheses, so that you can add the least square brackets to match the string.
Idea: DP in the blacklist. DP [I] [J] = min {DP [I + 1] [J-1] (SH [I] = sh [J]), DP [I] [k] + dp [k + 1] [J] (I <= k <j )}. recursive output, in fact, I think the output is much harder than the DP part .....
1 # include <stdio. h> 2 # include <string. h> 3 # include <iostream> 4 5 using namespace STD; 6 7 char sh [110]; 8 int DP [110] [110], Mark [110] [110]; 9 // The DP array represents the minimum number of parentheses to be added from I to J, the Mark array indicates that adding parentheses at the mark [I] [J] position from I to J can make the number of parentheses to be added at least 10 11 void print (int I, Int J) 12 {13 if (I> J) return; 14 else if (I = J) 15 {16 if (SH [I] = '(' | sh [I] = ') 17 printf ("()"); 18 else printf ("[]"); 19} 20 else if (MARK [I] [J] =-1) 21 {22 printf ("% C ", sh [I]); 23 print (I + 1, J-1); 24 printf ("% C", SH [J]); 25} 26 else27 {28 print (I, mark [I] [J]); 29 print (MARK [I] [J] + 1, J); 30} 31} 32 int main () 33 {34 while (gets (SH) 35 {36 int Len = strlen (SH); 37 memset (DP, 0, sizeof (DP )); 38 for (INT I = 0; I <Len; I ++) 39 {40 DP [I] [I] = 1; 41} 42 for (INT L = 1; L <Len; l ++) // a large interval is introduced from a small interval. The enumerated length is 43 {44 int temp = len-L; 45 for (INT I = 0; I <temp; I ++) 46 {47 Int J = I + L; 48 DP [I] [J] = 99999999; 49 If (SH [I] = '(' & SH [J] = ')') | (SH [I] = '[' & SH [J] = ']') 50 {51 DP [I] [J] = DP [I + 1] [J-1]; 52 mark [I] [J] =-1; 53} 54 for (int K = I; k <j; k ++) 55 {56 int temp1 = DP [I] [k] + dp [k + 1] [J]; 57 if (DP [I] [J]> = temp1) 58 {59 DP [I] [J] = temp1; 60 mark [I] [J] = K; 61} 62} 63} 64} 65 print (0, len-1 ); 66 puts (""); 67} 68 return 0; 69}View code
Ural 1183 brackets sequence (DP)