51nod 1791 合法括號子段(DP)

[1791 合法括號子段]
有一個括號序列,現在要計算一下它有多少非空子段是合法括號序列。
合法括號序列的定義是:
1.空序列是合法括號序列。
2.如果S是合法括號序列,那麼(S)是合法括號序列。
3.如果A和B都是合法括號序列,那麼AB是合法括號序列。

Input
多組測試數據。
第一行有一個整數T(1<=T<=1100000),表示測試數據的數量。
接下來T行,每一行都有一個括號序列,是一個由’(‘和’)’組成的非空串。
所有輸入的括號序列的總長度不超過1100000。
Output
輸出T行,每一行對應一個測試數據的答案。
Input示例
5
(
()
()()
(()
(())
Output示例
0
1
3
1
2

Code:

/*******************************************
 *Author: xiaoran
 *Time: 2017-09-04 12:53:00
 *ProblemID: 51nod1791
 *
 *Algorithm:
 *1、找到所有'('對應的')'的位置,例如 s[i] = '(' --> s[pos[i]] = ')',使用棧計算
 *2、合法的子串一定從某個'('開始,例如位置是i,對應的')'的位置是pos[i],[i,pos[i]]是合法字符串
 *   dp[i]:表示從n到i的合法的字符串的個數,那麼dp[i] = dp[pos[i]+1] + 1
 *3、從n-->1掃描一下,對所有從'('開始的位置i求和。
 *
 *Introduction:
 *
 *TimeComplex:
 *MemoryComplex:
 ******************************************/
#include<iostream>
#include<string.h>
#include<string>
#include<stack>
#include<algorithm>
#include<stdio.h>
using namespace std;
const int MAXN = 1100005;
typedef long long LL;
int pos[MAXN];
LL dp[MAXN];
char s[MAXN];

int main()
{
    int t;
//    cin>>t;
    scanf("%d",&t);
    while(t--){
        scanf("%s",s);
        int len = strlen(s);
        stack<int> sta;//存儲所有的'('的位置

        for(int i=0;i<=len;i++){
            pos[i] = -1;
            dp[i] = 0;
        }
        for(int i=0;i<len;i++){

            if(s[i] == '('){
                sta.push(i);
            }
            else{//s[i] == ')'
                if(!sta.empty()){
                    pos[sta.top()] = i;
                    sta.pop();
                }
            }
        }
        LL result = 0;
        dp[len] = 0;
        for(int i=len-1;i>=0;i--){
            if(pos[i] == -1) continue;

            dp[i] = dp[pos[i]+1] + 1;
            result += dp[i];

        }
        printf("%lld\n",result);
    }


    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章