1791 valid bracket segments __ Dynamic Programming

Source: Internet
Author: User
1791 Valid Bracket sub-paragraph Description there is a sequence of parentheses, and now it's time to calculate how many of the non-empty segments are valid bracket sequences. the definition of a valid bracket sequence is:

1. The empty sequence is the valid bracket sequence.
2. If s is the valid bracket sequence, then (s) is the valid bracket sequence.
3. If A and B are both valid parentheses, then AB is the valid bracket sequence. Input multiple sets of test data. the first line has an integer T (1<=t<=1100000) that represents the number of test data. next T line, each row has a sequence of parentheses, which is a non-empty string composed of ' (' and ') '. the total length of all entered brackets is no more than 1100000. output t row, each row corresponds to the answer to a test data. Input Sample

5
(
()
()()
(()
(()) output Sample

0
1
3
1
2 Solution

A magical DP problem, in fact, is also very good, because for each of them ' (' can only find a match ') '. Obviously, in the case where the bracket string is fixed, the parentheses match is fixed. With this strategy, we can first use the stack to match the parentheses, P[i] represents the position of the brackets matching the I bracket, easy to get the DP equation ans[i]=ans[p[i]+1]+1, and then the line sweep the sum.

 #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; }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.