POJ 1141 Brackets Sequence(DP)

8370 단어 sequence
Brackets Sequence
Time Limit: 1000MS
 
Memory Limit: 65536K
Total Submissions: 18313
 
Accepted: 5020
 
Special Judge
Description
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
()[()]

Source
Northeastern Europe 2001
 
 
 
 
제목 설명:
(,), [,]로 구성된 문자열을 주고 최소한의 괄호를 추가하여 모든 괄호를 일치시키고 마지막에 얻은 문자열을 출력합니다.
문제 해결 방법:
DP로 최소 괄호 수를 구합니다: p로 1부터 n (문자열 길이) 까지 i에서 i+p까지 추가해야 하는 최소 괄호 수 f[i][j]를 기록하고 중간에 괄호를 추가해야 하는 위치pos[i][j]를 기록합니다. -1은 추가할 필요가 없음을 나타냅니다.
 
 
DP
 
 
#include<stdio.h>
#include<string.h>

#define MAXN 120
const int INF=0x7fffffff;

int f[MAXN][MAXN],pos[MAXN][MAXN];
char s[MAXN];

int n;

int DP()
{
n=strlen(s);
memset(f,0,sizeof(f));

for(int i=n;i>0;i--)
{
s[i]=s[i-1];
f[i][i]=1;
}
int tmp;
for(int p=1;p<=n;p++)
{
for(int i=1;i<=n-p;i++)
{
int j=i+p;
f[i][j]=INF;
if((s[i]=='('&&s[j]==')')||(s[i]=='['&&s[j]==']'))
{
tmp=f[i+1][j-1];
if(tmp<f[i][j])
f[i][j]=tmp;
}
pos[i][j]=-1;
for(int k=i;k<j;k++)
{
tmp=f[i][k]+f[k+1][j];
if(tmp<f[i][j])
{
f[i][j]=tmp;
pos[i][j]=k;
}
}
}
}
return f[1][n];
}

void print(int beg,int end)
{
if(beg>end)return ;
if(beg==end)
{
if(s[beg]=='('||s[beg]==')')
printf("()");
else printf("[]");
}
else
{
if(pos[beg][end]==-1)
{
if(s[beg]=='(')
{
printf("(");
print(beg+1,end-1);
printf(")");
}
else
{
printf("[");
print(beg+1,end-1);
printf("]");
}
}
else
{
print(beg,pos[beg][end]);
print(pos[beg][end]+1,end);
}
}
}
int main()
{
// while(scanf("%s",&s)!=EOF) // WR
scanf("%s",&s);

DP();
print(1,n);
printf("
");

return 0;
}

좋은 웹페이지 즐겨찾기