您的位置:首页 > 产品设计 > UI/UE

POJ 1141 Brackets Sequence(动态规划 / 递归)

2018-02-21 12:35 495 查看

Brackets Sequence (POJ 1141)

Time Limit: 1000MS Memory Limit: 65536K

Total Submissions: 33360 Accepted: 9662 Special Judge

Description

Let us define a regular brackets sequence in the following way:

Empty sequence is a regular sequence.

If S is a regular sequence, then (S) and [S] are both regular sequences.

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,但我没想到要怎么打印。然后参考了别人的博客,才知道用pos[][]来存储最优分离点的坐标。然后递归打印pos分割的串。

//#include <bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <iostream>
4000
;
using namespace std;
const int MAXN = 256;
char str[MAXN];
int dp[MAXN][MAXN],pos[MAXN][MAXN];
int l,r;
bool h(char a,char b)
{
if(a == '(' && b == ')')return true;
if(a == '[' && b == ']')return true;
return false;
}
void print(int i, int j)
{
if(i > j)return ;
if(i == j)
{
if(str[i] == '(' || str[j] == ')')
{
printf("()");
}
else
{
printf("[]");
}
}
else if(pos[i][j] == -1)
{
printf("%c",str[i]);
print(i+1,j-1);
printf("%c",str[j]);
}
else
{
print(i,pos[i][j]);
print(pos[i][j] + 1,j);
}

}
int main()
{
while(gets(str))
{
int len;
len = strlen(str);
memset(dp,0,sizeof(dp));
for(int i = 0; i < len; i++)
{
dp[i][i] = 1;
}
int j;
for(int k = 1; k < len; k++)
{
for(int i = 0; i + k < len; i++)
{
j = i + k;
dp[i][j] = 0x7fffffff;
if(h(str[i],str[j]))
{
dp[i][j] = dp[i+1][j-1];
pos[i][j] = -1;
}
for(int mid = i; mid <j; mid++)
{
if(dp[i][j] > dp[i][mid] + dp[mid+1][j])
{
dp[i][j] = dp[i][mid] + dp[mid+1][j];
pos[i][j] = mid;
}
}
}
}
print(0,len-1);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: