State Representation Method: d [I] [J] indicates the start and end of a sequence;
State definition: d [I] [J] indicates the string s [I ~ J] quantity to be added.
# Include <cstdio> # include <cstring> # include <algorithm> using namespace STD; int N; char s [105]; int d [105] [105]; bool match (char character, char CH2) {If (character = '[' & CH2 = ']') | (character = '(') & CH2 = ') return true; return false;} void dp () {for (INT I = 0; I <n; I ++) {d [I + 1] [I] = 0; d [I] [I] = 1;} For (INT I = n-2; I> = 0; I --) {for (Int J = I + 1; j <n; j ++) {d [I] [J] = N; If (MATCH (s [I], s [J]) d [I] [J] = min (d [I] [J], d [I + 1] [J-1]); for (int K = I; k <J; k ++) d [I] [J] = min (d [I] [J], d [I] [k] + d [k + 1] [J]) ;}} void print (int I, Int J) {if (I> J) return; if (I = J) {If (s [I] = '(' | s [J] = ') printf ("()"); else printf ("[]"); return;} int ans = d [I] [J]; If (MATCH (s [I], s [J]) & Ans = d [I + 1] [J-1]) {printf ("% C", s [I]); print (I + 1, J-1 ); printf ("% C", s [J]); Return ;}for (int K = I; k <j; k ++) {If (ANS = d [I] [k] + d [k + 1] [J]) {print (I, K); print (k + 1, j); Return ;}} int main () {Int t; scanf ("% d", & T); getchar (); For (INT Kase = 1; Kase <= T; Kase ++) {gets (s); n = strlen (s); If (n = 0) {printf ("\ n"); If (Kase! = T) printf ("\ n"); continue;} dp (); print (0, n-1); printf ("\ n"); If (Kase! = T) printf ("\ n");} return 0 ;}
For this question, this is a question about matching brackets. There are many questions about the matching of parentheses, and they are implemented using stacks. We also want to use dynamic rules to record the State implementation.
It is hard to define the status, and it is hard to define the status transfer. However, there are so many bad ideas.
If you have learned to do this, remember it.