G - Brackets Sequence
Let us define a regular brackets sequence in the following way:
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
The input file contains at most 100 brackets (characters '(', ')', '[' and ']') that are situated on a single line without any other characters among them.
Output
Write to the output file a single line that contains some regular brackets sequence that has the minimal possible length and contains the given sequence as a subsequence.
Sample Input
([(]
Sample Output
()[()]
动态规划,用dp[i][j]保存从第i个字符(从零开始算)到第j个字符间形成完整regular sequences需要添加的字符个数,pos[i][j]表示形成第i个字符(从零开始算)到第j个字符间形成完整regular sequences需要断开而形成的题目所说的AB的形式的分界点(该点为A的右端),枚举过程i到j的长度是从小到大的,因此计算第i个字符到第j个字符时,在(i,j)位置的dp值是可知的,具体看代码,不难理解
#include<cstdio>
#include<stack>
#include<set>
#include<vector>
#include<queue>
#include<algorithm>
#include<cstring>
#include<string>
#include<map>
#include<iostream>
#include<cmath>
using namespace std;
#define inf 0x3f3f3f3f
typedef long long ll;
const int N=300;
const double esp = 1e-9;
const double PI=3.1415926;
char ch[N];
int dp[N][N],pos[N][N];
void solve(int i,int j)
{
if(i>j)
return;
if(i==j)
{
if(ch[i]=='('||ch[j]==')')
printf("()");
else
printf("[]");
}
else if(pos[i][j]==-1)
{
printf("%c",ch[i]);
solve(i+1,j-1); //递归中间部分的过程
printf("%c",ch[j]);
}
else
{
solve(i,pos[i][j]);
solve(pos[i][j]+1,j);
}
}
int main()
{
while(gets(ch)!=NULL) //不能用scanf输入,scanf不能输入带空格字符串
{
int len=strlen(ch);
memset(dp,0,sizeof(dp));
for(int i=0; i<len; i++)
{
dp[i][i]=1;
}
for(int t=1; t<len; t++)
{
for(int i=0; i+t<len; i++)
{
int j=i+t;
dp[i][j]=inf;
if((ch[i]=='('&&ch[j]==')')||(ch[i]=='['&&ch[j]==']'))
{
dp[i][j]=dp[i+1][j-1];
pos[i][j]=-1;
}
for(int mid=i; mid<j; mid++) //计算是否有更优解
{
int ans=dp[i][mid]+dp[mid+1][j];
if(dp[i][j]>ans)
{
pos[i][j]=mid;
dp[i][j]=ans;
}
}
}
}
solve(0,len-1);
printf("\n");
}
return 0;
}