动态规划--合法括号字段

题目来源:51node 1791

题意:找出合法子字符串的个数,先找出每个‘(’对应的‘)’位置,从后往前扫求和。

代码:

/*****************************************************
*Author:chenxi
*method: s[i]如果是'(',那么pos[i]代表的是与之匹配到的')'位置 
*dp[pos[i]]代表的是合法字符串的数目,从n到i的合法字符串个数 
*dp[i] = dp[pos[i]+1]+1 
*
******************************************************/
#include <iostream>
#include <string.h>
#include <string>
#include <cstdio>    
#include <stack>
using namespace std;
typedef long long ll;
const int maxn = 1100005;

ll dp[maxn],pos[maxn];
//string s;
char s[maxn];
ll sum = 0;
int main()
{
    ll t;
    scanf("%lld",&t);
    while(t--){
        sum = 0;
        scanf("%s",s);
        int len = strlen(s);
        stack<int> kuohao;  //'('
        for(int i = 0;i <= len;++i){
            pos[i] = -1;
            dp[i] = 0;
        }
        for(int i = 0;i < len;++i){
            if( s[i]=='(' ) kuohao.push(i);
            else{
                if( !kuohao.empty() ){
                    pos[kuohao.top()] = i;
                    kuohao.pop();
                }
            
            } 
        }
        for(int i = len-1;i >= 0;--i){
            if( pos[i]==-1 ) continue;
            dp[i] = dp[pos[i]+1]+1;
            sum += dp[i];
        }
    printf("%lld
",sum);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/chenxi0x0/p/9720326.html