【poj2955】Brackets

题目描述

有 “(” “)” “[” “]”四种括号,问在一组括号序列中有多少括号完全匹配。

样例输入

((()))
()()()
([]])
)[)(
([][][)
end


样例输出

6
6
4
0
6



题解

dp[ i ][ j ]表示 i -> j 中的匹配数,那么如果s[ i-1 ]与s[ j+1 ]配对,则dp[ i-1 ][ j+1 ]=dp[ i ][ j ]+2。然后区间dp。

#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long

const int maxn=100+5;

int dp[maxn][maxn];
char s[maxn];

template<typename T>void read(T& aa) {
    char cc; ll ff;aa=0;cc=getchar();ff=1;
    while((cc<'0'||cc>'9')&&cc!='-') cc=getchar();
    if(cc=='-') ff=-1,cc=getchar();
    while(cc>='0'&&cc<='9') aa=aa*10+cc-'0',cc=getchar();
    aa*=ff;
}

int main(){
    int n;
    while(cin>>s+1&&s[1]!='e'){
        memset(dp,0,sizeof(dp));
        n=strlen(s+1);
        for(int i=n-1;i>=1;i--)
        for(int j=i;j<=n;j++){
            if((s[i]=='('&&s[j]==')')||(s[i]=='['&&s[j]==']')){
                dp[i][j]=dp[i+1][j-1]+2;
            }
            for(int k=i;k<j;k++)
            dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]);
        }
        cout<<dp[1][n]<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/rlddd/p/9465000.html