如题:http://poj.org/problem?id=1141
Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 26530 | Accepted: 7488 | Special Judge |
Description
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
Output
Sample Input
([(]
Sample Output
()[()]
Source
题意:匹配括号。(),[]. 加入最小的数量的括号使得某一个字符串匹配。
思路:dp[i][j]:当前区间[i,j]最少要加入几个括号使得区间全部匹配。
当str[i]==str[j],dp[i][j]=dp[i+1][j-1].
else dp[i][j]=dp[i][k]+dp[k+1][j].(i<=k<j).
初始化dp[i][i]=1.
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define MAXN 105
#define INF 0x0fffffff
char str[MAXN];
int dp[MAXN][MAXN];
int path[MAXN][MAXN];
void print(int i,int j)
{
if(i>j)
return;
if(i==j)
{
if(str[i]=='['||str[i]==']')
printf("[]");
else
printf("()");
}
else if(path[i][j]==-1)
{
printf("%c",str[i]);
print(i+1,j-1);
printf("%c",str[j]);
}
else
{
print(i,path[i][j]);
print(path[i][j]+1,j);
}
}
int main()
{
while(gets(str))
{
memset(dp,0,sizeof(dp));
memset(path,0,sizeof(path));
int i,j,k;
int n=strlen(str);
if(n==0)
{
printf("\n");
continue;
}
for(i=0;i<n;i++)
dp[i][i]=1;
for(i=1;i<n;i++)
for(j=0;j<n-i;j++)
{
int m=j+i;
dp[j][m]=INF;
if((str[j]=='('&&str[m]==')')||(str[j]=='['&&str[m]==']'))
if(dp[j][m]>dp[j+1][m-1])
{
dp[j][m]=dp[j+1][m-1];
path[j][m]=-1;
}
for(k=j;k<m;k++)
{
if(dp[j][m]>dp[j][k]+dp[k+1][m])
{
dp[j][m]=dp[j][k]+dp[k+1][m];
path[j][m]=k;
}
}
}
print(0,n-1);
printf("\n");
}
return 0;
}