题目:
Brackets Sequence
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 35575 Accepted: 10287 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,dp[i][j]表示的是i到j这个区间里面要补充的最小字符数,那么对于区间之间的每个位置k,很容易推出状态转移方程为dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]),每一次的更新都在这个区间标记下断点的那个k的位置。
同时如果str[i]与str[j]是匹配的,那么还要加上一个特殊的判断,dp[i][j]=min(dp[i][j],dp[i+1][j-1]+2),如果更新了dp的值,那么就需要再把原本标记的位置取消掉(设置成-1)。
这题的输出需要写一个dfs来根据标记记录的位置来输出字符串。
感觉是一个区间dp的不错的题目。
AC代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long ll;
const int maxn=1e5+5;
int n,m;
int t;
double a,b;
int dp[105][105];
int rec[105][105];
string str;
string s;
//没过掉
void print(int l,int r)
{
if(r<l) return;
if(l==r)
{
if(s[l]=='('||s[l]==')')
printf("()");
else
printf("[]");
return;
}
if(rec[l][r]==-1)
{
if(s[l]=='(')
{
printf("(");
print(l+1,r-1);
printf(")");
}
else
{
printf("[");
print(l+1,r-1);
printf("]");
}
}
else
{
print(l,rec[l][r]);
print(rec[l][r]+1,r);
}
}
int main()
{
cin>>str;
int len=str.size();
s=str;
memset(dp,0x3f,sizeof(dp));
memset(rec,-1,sizeof(rec));
for(int i=0;i<len;i++)
dp[i][i]=2;
for(int i=1;i<len;i++)
{
for(int j=0;j+i<len;j++)//j是左端点,i是长度,j+i是右端点
{
for(int k=j;k<=j+i;k++)
{
if(dp[j][j+i]>dp[j][k]+dp[k+1][j+i])
{
dp[j][j+i]=dp[j][k]+dp[k+1][j+i];
rec[j][j+i]=k;
}
}
if((str[j]=='('&&str[j+i]==')')||(str[j]=='['&&str[j+i]==']'))
{
if(dp[j][j+i]>dp[j+1][j+i-1]+2)
{
dp[j][j+i]=dp[j+1][j+i-1]+2;
rec[j][j+i]=-1;
}
}
}
}
print(0,len-1);
printf("\n");
return 0;
}