题目链接
http://poj.org/problem?id=1141
Description
1. Empty sequence is a regular sequence.
2. If S is a regular sequence, then (S) and [S] are both regular sequences.
3. If A and B are regular sequences, then AB is a regular sequence.
For example, all of the following sequences of characters are regular brackets sequences:
(), [], (()), ([]), ()[], ()[()]
And all of the following character sequences are not:
(, [, ), )(, ([)], ([(]
Some sequence of characters '(', ')', '[', and ']' is given. You are to find the shortest possible regular brackets sequence, that contains the given character sequence as a subsequence. Here, a string a1 a2 ... an is called a subsequence of the string b1 b2 ... bm, if there exist such indices 1 = i1 < i2 < ... < in = m, that aj = bij for all 1 = j = n.
Input
Output
Sample Input
([(]
Sample Output
()[()]
Source
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
const int inf=0x3f3f3f3f;
char s[];
int v[][];
int dp[][]; void print(int l,int r)
{
if(r<l) return;
if(l==r)
{
if(s[l]=='('||s[l]==')')
printf("()");
else
printf("[]");
return;
}
if(v[l][r]==-)
{
if(s[l]=='(')
{
printf("(");
print(l+,r-);
printf(")");
}
else
{
printf("[");
print(l+,r-);
printf("]");
}
}
else
{
print(l,v[l][r]);
print(v[l][r]+,r);
}
} int main()
{
scanf("%s",s);
int len=strlen(s);
memset(dp,,sizeof(dp));
for(int i=; i<len; i++)
dp[i][i]=; for(int l=; l<len; l++)
{
for(int i=; i+l<len; i++)
{
dp[i][i+l]=inf;
for(int k=i; k<i+l; k++)
{
if(dp[i][i+l]>dp[i][k]+dp[k+][i+l])
{
dp[i][i+l]=dp[i][k]+dp[k+][i+l];
v[i][i+l]=k;
}
}
if(s[i]=='('&&s[i+l]==')'||s[i]=='['&&s[i+l]==']')
{
if(dp[i][i+l]>dp[i+][i+l-]+)
{
dp[i][i+l]=dp[i+][i+l-]+;
v[i][i+l]=-;
}
}
}
}
print(,len-);
printf("\n");
return ;
}