1183. Brackets Sequence
Time limit: 1.0 second
Memory limit: 64 MB
Let us define a regular brackets sequence in the following way:
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 a
1a
2...a
n is called a subsequence of the string b
1b
2...b
m, if there exist such indices 1 ≤ i
1 < i
2 < ... < i
n ≤ m, that a
j=b
ij for all 1 ≤ j ≤ n.
Input
The input contains at most 100 brackets (characters '(', ')', '[' and ']') that are situated on a single line without any other characters among them.
Output
Write a single line that contains some regular brackets sequence that has the minimal possible length and contains the given sequence as a subsequence.
Sample
|
#include <map>
#include <set>
#include <list>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <vector>
#include <bitset>
#include <cstdio>
#include <string>
#include <numeric>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
int dx[4]= {-1,1,0,0};
int dy[4]= {0,0,-1,1}; //up down left right
bool inmap(int x,int y,int n,int m)
{
if(x<1||x>n||y<1||y>m)return false;
return true;
}
int hashmap(int x,int y,int m)
{
return (x-1)*m+y;
}
#define eps 1e-8
#define inf 0x7fffffff
#define debug puts("BUG");
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define Read freopen("in.txt","r",stdin)
#define Write freopen("out.txt","w",stdout)
char str[200]= {0};
int dp[110][110]= {0},len;
int tag[111][111]= {0};
void read()
{
scanf("%s",str);
}
void print(int s,int e)
{
if (s>e)return;
if (s==e)
{
if (str[s]=='(' || str[s]==')')
printf("()");
else
printf("[]");
return ;
}
if (tag[s][e]==-1)
{
printf("%c",str[s]);
print(s+1,e-1);
printf("%c",str[e]);
}
else
{
print(s,tag[s][e]);
print(tag[s][e]+1,e);
}
}
void DP()
{
len = strlen(str);
for (int i=0; i<len; i++)
{
dp[i][i]=1;//初始
dp[i+1][i]=0;//下面在进行DP时,i=j+1时,i=i+1、j=j-1会造成i=j+1
}
for (int st=1; st<len; st++)
{
for (int i=0; i+st<len; i++)
{
int j=i+st;
int temp=9999999;
if ((str[i]=='(' && str[j]==')')||(str[i]=='[' && str[j]==']'))
{
temp=dp[i+1][j-1];//第一种情况(s)或[s]
}
tag[i][j]=-1;
for (int k=i; k<j; k++) //第二种情况,枚举i到j之间的k 即AB
{
int res=dp[i][k]+dp[k+1][j];
if (res<temp)
{
temp=res;
tag[i][j]=k;
}
}
dp[i][j]=temp;
}
}
print(0,len-1);//根据标记情况进行回溯
printf("\n");
}
int main()
{
read();
DP();
return 0;
}