Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 13305 | Accepted: 3585 | Special Judge |
Description
Input
Output
Sample Input
([(]
Sample Output
()[()]
Source
/*
http://acm.pku.edu.cn/JudgeOnline/problem?id=1141
动态规划,与最优二叉查找树类似,从下往上,从小到大,遍历长度len,然后遍历位置k
*/
#include <iostream>
#define MAX_N 100
using namespace std;
char input[MAX_N + 1];
int len;
int pos[MAX_N + 1][MAX_N + 1];
int minV[MAX_N + 1][MAX_N + 1];
void print(int f, int t)
{
if(f > t)
return;
if(pos[f][t] == -1)
{
cout<<input[f];
print(f + 1, t - 1);
cout<<input[t];
}
else if(f == t)
{
char type = input[f];
if(type == ')' || type == '(')
cout<<"()";
else
cout<<"[]";
}
else
{
print(f, pos[f][t]);
print(pos[f][t] + 1, t);
}
}
bool match(char t1, char t2)
{
return ((t1 == '(' && t2 == ')') || (t1 == '[' && t2 == ']'));
}
int main()
{
char ch;
len = 0;
while((ch = getchar()) != 10)
{
input[++len] = ch;
}
int i, j;
for(i = 1; i <= len; i++)
{
for(j = 1; j <= len; j++)
{
if(i == j)
minV[i][j] = 1;
}
}
int l, k;
for(l = 2; l <= len; l++)
{
for(i = 1; i <= len - l + 1; i++)
{
j = i + l - 1;
int minVal = INT_MAX, minPos = 0, curVal;
for(k = i; k < j; k++)
{
curVal = minV[i][k] + minV[k + 1][j];
if(curVal < minVal)
{
minVal = curVal;
minPos = k;
}
}
if(match(input[i], input[j]))
{
curVal = minV[i + 1][j - 1];
if(curVal < minVal)
{
minVal = curVal;
minPos = -1; //min trim head and tail
}
}
minV[i][j] = minVal;
pos[i][j] = minPos;
}
}
print(1, len);
cout<<endl;
return 0;
}