poj1141 2010.7.31
Brackets Sequence
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 12467 Accepted: 3338 Special Judge
Description
Let us define a regular brackets sequencein 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, thenAB is a regular sequence.
For example, all of the following sequencesof characters are regular brackets sequences:
(), [], (()), ([]), ()[], ()[()]
And all of the following charactersequences are not:
(, [, ), )(, ([)], ([(]
Some sequence of characters '(', ')', '[',and ']' is given. You are to find the shortest possible regular bracketssequence, that contains the given character sequence as a subsequence. Here, astring a1 a2 ... an is called a subsequence of the string b1 b2 ... bm, ifthere exist such indices 1 = i1 < i2 < ... < in = m, that aj = bij forall 1 = j = n.
Input
The input file contains at most 100brackets (characters '(', ')', '[' and ']') that are situated on a single linewithout any other characters among them.
Output
Write to the output file a single line thatcontains some regular brackets sequence that has the minimal possible lengthand contains the given sequence as a subsequence.
Sample Input
([(]
Sample Output
()[()]
Source
Northeastern Europe 2001
详见lrj的黑书
不过,记录下来答案,用到c++里的<string>真的很不错~~~可以直接对字符串用+ 来衔接,不错~~~
ans[i][j]表示 i..j这断填好括号后的序列
WA 因:
1.dp方程敲成代码的时候,一激动敲错了
2.把"[]" 敲成了 ‘[]' ,酱紫就是字符,不是字符串了。。。
Source Code
Problem: 1141 User: creamxcream
Memory: 1020K Time: 391MS
Language: C++ Result: Accepted
Source Code
#include <string>
#include <cstdio>
#include <cstring>
#include <iostream>
#define INF ~0U>>1
using namespace std;
#define MAXN 106
string ans[MAXN][MAXN];
int dp[MAXN][MAXN];
char str[MAXN];
int n,flag=0;
void init()
{
memset(dp,0,sizeof(dp));
cin.getline(str+1,MAXN);
n=strlen(str+1);
if (n==0)
{
flag=1;
return;
}
for(int i=0;i<=n;i++)
{
dp[i][i]=1;
if ((str[i]=='(')||(str[i]==')'))
ans[i][i]="()";
else
ans[i][i]="[]";
}
}
void dpit()
{
for(int p=1;p<=n-1;p++)
for(int i=1;i<=n-p;i++)
{
int j=i+p;
dp[i][j]=INF;
if (((str[i]=='(')&&(str[j]==')'))||
((str[i]=='[')&&(str[j]==']')))
if (dp[i+1][j-1]<dp[i][j])
{
dp[i][j]=dp[i+1][j-1];
ans[i][j]=str[i]+ans[i+1][j-1]+str[j];
}
if ((str[i]=='(')||(str[i]=='['))
if (dp[i+1][j]+1<dp[i][j])
{
dp[i][j]=dp[i+1][j]+1;
if (str[i]=='(')
ans[i][j]='('+ans[i+1][j]+')';
else
ans[i][j]='['+ans[i+1][j]+']';
}
if ((str[j]==')')||(str[j]==']'))
if (dp[i][j-1]+1<dp[i][j])
{
dp[i][j]=dp[i][j-1]+1;
if (str[j]==')')
ans[i][j]='('+ans[i][j-1]+')';
else
ans[i][j]='['+ans[i][j-1]+']';
}
for (int k=i;k<=j-1;k++)
{
if (dp[i][k]+dp[k+1][j]<dp[i][j])
{
dp[i][j]=dp[i][k]+dp[k+1][j];
ans[i][j]=ans[i][k]+ans[k+1][j];
}
}
}
}
int main()
{
init();
if (flag==1)
{
printf("\n");
}
else
{
dpit();
cout<<ans[1][n]<<endl;
}
return 0;
}