原题链接:http://poj.org/problem?id=1141
题意:给一个不规则的字符串,求添加最少的字符使其成为一个规则的字符串
#define _CRT_SECURE_NO_DEPRECATE
#include<iostream>
#include<vector>
#include<cstring>
#include<queue>
#include<stack>
#include<algorithm>
#include<cmath>
#include<string>
#define INF 99999999
#define eps 0.0001
using namespace std;
int len;
char s[105];
int v[105][105];
int dp[105][105];
void DP()
{
for (int i = 0; i < len; i++)
dp[i][i] = 1;
for (int l = 1; l < len; l++)
{
for (int i = 0; i + l < len; i++)
{
int j = i + l;
dp[i][j] = INF;
if ((s[i] == '('&&s[j] == ')') || (s[i] == '['&&s[j] == ']'))
{
dp[i][j] = dp[i + 1][j - 1];
v[i][j] = -1;
}
for (int k = i; k < j; k++)
{
if (dp[i][j]>dp[i][k] + dp[k + 1][j])
{
dp[i][j] = dp[i][k] + dp[k + 1][j];
v[i][j] = k;
}
}
}
}
}
void print(int i, int j)
{
if (i > j)
return;
else if (i == j)
{
if (s[i] == '(' || s[i] == ')')
printf("()");
else
printf("[]");
}
else if (v[i][j] == -1)
{
printf("%c", s[i]);
print(i + 1, j - 1);
printf("%c", s[j]);
}
else
{
print(i, v[i][j]);
print(v[i][j] + 1, j);
}
}
int main()
{
while (scanf("%s", s) != EOF)
{
memset(dp, 0, sizeof(dp));
len = strlen(s);
DP();
print(0, len - 1);
printf("\n");
}
return 0;
}