poj1141 dp

31 篇文章 0 订阅

 

 

如题:http://poj.org/problem?id=1141

Brackets Sequence
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 26530 Accepted: 7488 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

 

题意:匹配括号。(),[].  加入最小的数量的括号使得某一个字符串匹配。

思路: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;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值