区间dp

来源:互联网 发布:网络代理app软件 编辑:程序博客网 时间:2024/06/05 20:07

题意

在一个含有”[ ]”,”( )”两种括号的串中寻找最长的合法序列。

样例

Sample Input

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

Sample Output

6
6
4
0
6

思路

区间dp,i为起始位置,j为结束位置,k为中间位置

dp[i][j]={max(dp[i][j],dp[i+1][k1]+2+dp[k+1][j]),max(dp[i][j],dp[i][k]+dp[k+1][j]),str[i]str[k]others

PS:不错的模板

#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>using namespace std;typedef long long LL;const int maxn=105;char st[maxn];int dp[maxn][maxn];int n;int main(){    while(~scanf("%s",st+1)){        memset(dp,0,sizeof(dp));        n=strlen(st+1);        if(st[1]=='e')break;        for(int L=2;L<=n;++L){            for(int i=1;i<=n-L+1;++i){                int j=i+L-1;                for(int k=i;k<=j;++k){                    if((st[i]=='('&&st[k]==')')||(st[i]=='['&&st[k]==']'))                        dp[i][j]=max(dp[i][j],dp[i+1][k-1]+2+dp[k+1][j]);                    else                        dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]);                }            }        }        printf("%d\n",dp[1][n]);    }    return 0;}
原创粉丝点击