/*
Bracket Matching (ii)
Time limit: Ms | Memory Limit: 65535 KB
Difficulty: 6
Describe
Give you a string that contains only "(", ")", "[", "]" four symbols, how many parentheses you need to add at least to make these parentheses match.
Such as:
[] is a match
([]) [] is a match
((] is not a match
([)] is mismatched
Input
The first line enters a positive integer N, which indicates the number of test data groups (N<=10)
Each set of test data has only one row, is a string s,s contains only the above mentioned four characters, the length of S is not more than 100
Output
Outputs a positive integer for each set of test data, representing the minimum number of parentheses to be added. One row per set of test outputs
Sample input
4
[]
([])[]
((]
([)]
Sample output
0
0
3
2
Interval DP, two-dimensional array storage The number of parentheses to be added, Dp[i][j] indicates the number of parentheses to be added from the I-bit to the J-bit interval,
When I==j, Dp[i][i] has only one parenthesis between the constituencies, so dp[i][i]=1;
Example: CC] length is 3
Need to find values in the interval (0,2)
(0,2) can be divided into (0,1), (2,2) or (0,0), whichever is the smallest
(0,2) (0,1) is divided into (0,0) () sub-interval (2,2)
(0,2) is divided into (four) (2,2) of the interval (0,0) to take the minimum
DP[I][J]
0 1 2
0 1 2 3
1 0 1 2
2 0 0 1
*/
#include <cstdio> #include <cstring> #include <algorithm> using namespace std;
const int MAX = 101;
int Dp[max][max];
Char s[101];
int main () {int n,i,j,k,width;
scanf ("%d", &n);
while (n--) {scanf ("%s", s);
int length = strlen (s);
Memset (Dp,0,sizeof (DP)); for (i = 0; i < length; i++) {dp[i][i] = 1; Only one character, matching one character} for (width = 1; width < length; width++)//Interval length {for (i = 0; i < length-width; i++)//interval start position {j = i + width;
Interval end position dp[i][j] = MAX; if ((s[i] = = ' (' && s[j] = = ') ') | | (S[i] = = ' [' && s[j] = = '] '))
Found in the interval of two pairs, the left and right intervals are reduced, in the value before the comparison dp[i][j] = min (dp[i][j],dp[i+1][j-1]); for (k = i; k < J; k++) {//divided into smaller interval dp[i][j] = min (dp[i][j],dp[i][k]+dP[K+1][J]);
}}} printf ("%d\n", dp[0][length-1]);
} return 0;
}