Corresponding Nyoj topic: Click to open link
Bracket Matching (ii) time limit: +Ms | Memory Limit:65535KB 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, s length does not exceed
-
-
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
-
-
0032
Idea: Interval DP. DP[I][J] represents the maximum number of matches (in multiples of 2) from the first position to the J position. The length of the string-dp[0][n-1] is the answer.
First, the adjacent matching brackets are initialized to dp[i][i+1] = 2; if str[i] matches str[j], then dp[i][j] = dp[i+1][j-1] + 2; Then there is the transfer equation: dp[i][j] = Max{dp[i][j], Dp[i][k] + DP[K+1][J]} (i <= k <j);
#include <stdio.h> #include <stdlib.h> #include <string.h> #define M 110#define MAX (x, y) ((x) > (y)? ( x): (y)) char str[m];int Dp[m][m];bool Check (char A, char b) {if (a = = ' [' && b = = '] ') return 1;if (A = = ' (' &&A mp b = = ') ' return 1;return 0;} int main () {//freopen ("In.txt", "R", stdin), int t;int L, I, J, K, len;scanf ("%d", &t), while (t--) {scanf ("%s", str); MEMS ET (DP, 0, sizeof (DP)), Len = strlen (str), for (i=0; i+1<len; i++) if (Check (Str[i], str[i+1])) dp[i][i+1] = 2;for (l=2; l< ; =len; l++) {for (i=0; i+l-1<len; i++) {j = i + l-1;if (Check (Str[i], str[j])) dp[i][j] = Dp[i+1][j-1] + 2;for (k=i; k+1<=j; k + +) {Dp[i][j] = MAX (Dp[i][j], dp[i][k] + dp[k+1][j]);}}} printf ("%d\n", Len-dp[0][len-1]);} return 0;}
Interval dp--bracket Matching