经典DP问题,注意输入不要使用while(xxx != EOF),否则WA,测试数据只有一组。同样的测试数据可能有多种答案。但最小长度唯一。一定不能用while,切记。
#include <iostream> using namespace std; #include <string> #define MAXNUM 200 #define MAXVAL 32767 string match(char []); int main() { string regstr; char str[MAXNUM]; cin >>str; regstr = match(str); cout <<regstr<<endl; return 0; } string match(char str[]) { string regstr[MAXNUM][MAXNUM]; int add[MAXNUM][MAXNUM]; int len = strlen(str); int i, j, k; memset(add, 0, sizeof(add)); for (i=0; i<len; i++) for (j=i; j<len; j++) { add[i][j] = MAXVAL; regstr[i][j] = ""; } for (i=len-1; i>=0; i--) { for (j=i; j<len; j++) { if (j == i) { add[i][j] = 1; if (str[i] == '(' || str[i] == ')') regstr[i][j] = "()"; if (str[i] == '[' || str[i] == ']') regstr[i][j] = "[]"; } else {if (str[i] == '(' && str[j] == ')') { add[i][j] = add[i+1][j-1]; regstr[i][j] = "(" + regstr[i+1][j-1] + ")"; } else if (str[i] == '[' && str[j] == ']') { add[i][j] = add[i+1][j-1]; regstr[i][j] = "[" + regstr[i+1][j-1] + "]"; } for (k=i; k<j; k++) { if (add[i][k]+add[k+1][j] < add[i][j]) { add[i][j] = add[i][k] + add[k+1][j]; regstr[i][j] = regstr[i][k] + regstr[k+1][j]; } } } } } return regstr[0][len-1]; }