poj 1141 Brackets Sequence 括号匹配

题意:给出一个由'(' , ')' ,'[' , ']' 组成的字符串,通过增加最少括号使其匹配。

解法:区间dp,记录下划分位置。PS:用while(scanf!=EOF)会WA

 

#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=105;
char str[maxn];
int dp[maxn][maxn], len, flag[maxn][maxn];
bool match(int x, int y){
    return (str[x]=='('&&str[y]==')')||(str[x]=='['&&str[y]==']');
}
void getmatch(int x){
    if(str[x]=='('||str[x]==')')printf("()");
    else printf("[]");
}
int solve(int x, int y){
    if(x>y)return 0;
    if(x==y)return 1;
    if(dp[x][y]!=-1)return dp[x][y];
    int i, tmp=maxn, s;
    for(i=x; i<y; i++){
        if(solve(x, i)+solve(i+1, y)<tmp){
            tmp=solve(x, i)+solve(i+1, y);
            s=i;
        }
    }
    if(match(x, y)&&solve(x+1, y-1)<tmp){
        tmp=solve(x+1, y-1);
        s=-1;
    }
    dp[x][y]=tmp;
    flag[x][y]=s;
    return tmp;
}

void solve2(int x, int y){
    if(x>y)return ;
    if(x==y){
        getmatch(x);
        return ;
    }
    if(flag[x][y]==-1){
        printf("%c", str[x]);
        solve2(x+1, y-1);
        printf("%c", str[y]);
    }
    else {
        solve2(x, flag[x][y]);
        solve2(flag[x][y]+1, y);
    }
}

int main(){
    scanf("%s", str);
    memset(dp, -1, sizeof(dp));
    len=strlen(str);
    solve(0, len-1);
    solve2(0, len-1);
    printf("\n");
    return 0;
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值