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
()[()]
思路:
這道題是 HUNNU oj 11757 Brackets 升級版,關於Brackets的題解,可以參考我的另一個博客:HUNNU oj 11757 Brackets————區間dp (括號匹配)
這裏我從Brackets的代碼基礎上加以改造。
這道題的要求是,給一段括號序列,添加最少的括號來使這個序列是匹配的。
我的思路是:先求出給出序列的最長匹配序列,如樣例 ([(] 的最長匹配序列就是 [], 即下標爲二和四的括號。然後用一個數組flag標記他們。之後將不匹配的(即沒有標記的)括號添加其對應的括號讓它匹配。然後就是結果。
具體就是在更新dp的同時更新flag就可以了。
flag[i][j][k]表示:區間[i , j]的最長序列的標記數組。
AC代碼:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define MAXN 105
#define INF 0x3f3f3f3f
using namespace std;
void CMP(bool a[], bool b[])
{
int i;
for(i = 0; i <= MAXN-1; i++)
{
a[i] = b[i];
}
}
void init(bool a[])
{
int i;
for(i = 0; i <= MAXN-1; i++)
{
a[i] = false;
}
}
int main()
{
bool flag[MAXN][MAXN][MAXN];
char a[MAXN];
gets(a);
int i, j, k, len, ti, n, dp[MAXN][MAXN];
n = strlen(a);
memset(dp, 0, sizeof(dp));
memset(flag, false, sizeof(dp));
for(len = 2; len <= n; len++)
{
for(i = 0; i <= n-1; i++)
{
int j = i+len-1;
if(j > n-1)
break;
if((a[i] == '(' && a[j] == ')') || (a[i] == '[' && a[j] == ']'))
{
dp[i][j] = dp[i+1][j-1] + 2;
CMP(flag[i][j], flag[i+1][j-1]);
flag[i][j][i] = true;
flag[i][j][j] = true;
}
for(k = i; k < j; k++)
{
if(dp[i][j] < dp[i][k] + dp[k+1][j])
{
dp[i][j] = dp[i][k] + dp[k+1][j];
init(flag[i][j]);
for(ti = i; ti <= k; ti++)
{
flag[i][j][ti] = flag[i][k][ti];
}
for(ti = k+1; ti <= j; ti++)
{
flag[i][j][ti] = flag[k+1][j][ti];
}
}
}
}
}
for(i = 0; i <= n-1; i++)
{
if(flag[0][n-1][i] == false)
{
if(a[i] == '(')
{
printf("%c", a[i]);
printf(")");
}
else if(a[i] == ')')
{
printf("(");
printf("%c", a[i]);
}
else if(a[i] == ']')
{
printf("[");
printf("%c", a[i]);
}
else if(a[i] == '[')
{
printf("%c", a[i]);
printf("]");
}
else
{
printf("%c", a[i]);
}
}
else
{
printf("%c", a[i]);
}
}
printf("\n");
return 0;
}