1791 合法括弧子段__動態規劃

來源:互聯網
上載者:User
1791 合法括弧子段 Description 有一個括弧序列,現在要計算一下它有多少非空子段是合法括弧序列。 合法括弧序列的定義是:

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 Solution

一道神奇的dp題,其實狀態也很好想,因為對於其中每個‘(’最多隻能找到一個與之相匹配的‘)’。顯然,在括弧串固定的情況下,括弧的匹配是固定不變的。有了這個策略,我們就可以先用棧將括弧匹配掉,p[i]表示與i這個括弧相匹配的括弧的位置,易得到dp方程 ans[i]=ans[p[i]+1]+1,再線掃一遍求和即可。

#include<cstdio>#include<algorithm>#include<cstring>using namespace std;int T,p[1100010],stuck[1100010],ans[1100010];char ch[1100010];int main(){    scanf("%d",&T);    while (T--){        scanf("%s",ch+1);        int l=strlen(ch+1),top=0;        long long num=0;        for (int i=1;i<=l;i++) p[i]=-1;        for (int i=1;i<=l;i++){            if (ch[i]=='(') stuck[++top]=i;            else if (top) p[stuck[top--]]=i;        }        for (int i=l;i>=1;i--)            if (p[i]==-1) ans[i]=0; else ans[i]=ans[p[i]+1]+1;        for (int i=1;i<=l;i++)            num+=ans[i];        printf("%lld\n",num);    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.