Title Link: Https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=847&page=show_ problem&problem=4501
Test instructions: Defines the following normal bracket sequence (string): The empty sequence is the normal bracket sequence, and if S is the normal bracket sequence, then (s) and [s] are also normal bracket sequences, and if both A and B are normal bracket sequences, then AB is also the normal bracket sequence. For example, the following string is the normal bracket sequence: (), [], (()), ([]), () [], () [()], and the following string is not a normal bracket sequence: (, [,],) (, [()]. Enter a sequence with a length of not more than 100, consisting of "(", ")", "[", "]", and add as few parentheses as possible to get a sequence of rules. If there is more than one solution, output any sequence. (This paragraph is excerpted from the "Algorithmic Competition Primer (2nd edition)")
Analysis:
Set the string s at least to increase the DP (S) bracket, which is transferred as follows:
1. If the S-shape (s ') or [s '] is transferred to DP (S ').
2. If S has at least two characters, it can be divided into AB and transferred to DP (A) +DP (B).
The boundary is: s is empty when D (s) =0,s is a single character when d (s) = 1. Whether S satisfies the first one, try the second one. Note that the input may be an empty string.
Code:
#include <iostream> #include <algorithm> #include <fstream> #include <string> #include < cstring> #include <vector> #include <queue> #include <cmath> #include <cctype> #include <
Stack> #include <set> using namespace std;
const int MAXN = + 5, INF = 1e9;
int T, n;
string S;
BOOL first;
int DP[MAXN][MAXN];
BOOL Match (char A, char b) {if (A = = ' (' && b = = ') ' | | a = = ' [' && b = = '] ') return true;
return false;
} void print (int i, int j) {if (i > J) return;
if (i = = j) {if (s[i] = = ' (' | | s[i] = = ') ') printf ("()");
else printf ("[]");
Return
} int ans = dp[i][j];
if (Match (S[i], s[j]) && ans = = dp[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 = = Dp[i][k] + dp[k + 1][j]) {print (I, k);
Print (k + 1, j);
Return
}} int main () {scanf ("%d%*c", &t); for (int C = 0; C < T;
++c) {if (first) printf ("\ n");
else first = true;
Getline (CIN, s);
Getline (CIN, s);
n = s.size ();
for (int i = 0; i < n; ++i) {dp[i + 1][i] = 0;
Dp[i][i] = 1;
} for (int i = n-2; I >= 0; i.) for (int j = i + 1; j < n; ++j) {
DP[I][J] = n;
if (Match (S[i], s[j])) dp[i][j] = min (Dp[i][j], dp[i + 1][j-1]);
for (int k = i; k < J; ++k) dp[i][j] = min (Dp[i][j], dp[i][k] + dp[k + 1][j]);
} print (0, n-1);
printf ("\ n");
} return 0;
}