Http://acm.nyist.net/JudgeOnline/problem.php? PID = 15
DP [I] [J] indicates the minimum number of parentheses to be added from I to J to meet the matching conditions.
Initialization:
If (I = J)
DP [I] [J] = 1;
Else
DP [I] [J] = inf;
Status transfer:
When I <J;
If (MATCH (STR [I], STR [J]) DP [I] [J] = min (DP [I] [J], d [I + 1] [J-1]);
Then split the interval and find the optimal split point K. (I <= k <= J );
DP [I] [J] = min (DP [I] [J], DP [I] [k] + dp [k + 1] [J]);
During the loop, the start point I and the length Len of the traversal interval (I... j) increase progressively from small to large.
That is, find the optimal solution for each interval starting from the I-length Len, and gradually expand to the entire interval. That is, the final solution of the problem!
#include <stdio.h>#include <string.h>#include <math.h>#include <iostream>#include <algorithm>#include <string>#include <queue>#include <stack>#include <vector>#include <list>#include <map>#include <set>#include <iomanip>#define CL(x,v); memset(x,v,sizeof(x));#define INF 1<<29#pragma comment(linker, "/STACK:1024000000,1024000000")using namespace std;const int N = 100 + 10;int dp[N][N];char str[N];int match(char ch1, char ch2){ if((ch1 == '(' && ch2 == ')') || (ch1 == '[' && ch2== ']')) return 1; return 0;}int main(){int t;scanf("%d", &t);while(t--) { CL(dp, 0); scanf("%s", str); int length = strlen(str); for(int i = 0; i < length; ++i) dp[i][i] = 1; for(int len = 1; len < length; ++len) { for(int i = 0; i < length - len; ++i) { int j = i + len; dp[i][j] = INF; if(match(str[i], str[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]); } } cout << dp[0][length - 1] << endl; } return 0;}
Nyoj15-bracket matching (2)-interval DP