Pairing through a bracket 1572

DP [i] [j] represents from i to j is paired Several

Two state transition points

  • dp[l][r]=max(dp[l+1][r-1]+2,dp[l][r]);

// + 2 matching pair of parentheses are completed, a total of two characters

  • dp[l][r]=max(dp[l][k]+dp[k+1][r],dp[l][r]);

// similar floyd

#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
#define N 105
char s[N];
int dp[N][N],n;
int main()
{
    scanf("%s",s+1);
    n=strlen(s+1);
    rep(i,1,n)
        for(int j=1;j+i-1<=n;j++)
        {
            int l=j,r=i+j-1;
            if((s[l]=='(' && s[r]==')' )|| (s[l]=='[' && s[r]==']'))
                dp[l][r]=max(dp[l+1][r-1]+2,dp[l][r]);
            rep(k,l,r-1)
                dp[l][r]=max(dp[l][k]+dp[k+1][r],dp[l][r]);
        }
    printf("%d\n",n-dp[1][n]);
    return 0;
}

Guess you like

Origin www.cnblogs.com/sjsjsj-minus-Si/p/11635599.html