Time limit:10000msSingle Point time limit:1000msMemory Limit:256MB
description
Yanshou County North listed "North City Park Exhibition Resort", is one of the three major cherry blossom Mutsu. Every year from mid-April to early May, there will be a grand memorial ceremony. In addition to the cherry blossom trails, you can take the sightseeing wagon Xu Xing, and the CARP flag across the North River, along with the local special borrowing strategy to worship the ancestors and the North Ghost Sword Dance.
Let's say we use a parenthesis string containing ' (', ') ' to distinguish the direction of each side of the CARP flag. A sequence of parentheses is called legal when and only if two conditions are met: first, for the entire sequence, the number of opening brackets equals the closing parenthesis; for any prefix, the number of opening brackets is not less than the number of closing parentheses. Island Niang want to know, for a string of parentheses, how many substrings are legal, you can help her.
Input
The input data is only one row, containing a length of n (1?≤? n ?? ≤?106) of the parentheses string.
Output
Outputs a row that represents the number of valid parentheses substrings.
-
Sample input
-
(()())
-
Sample output
-
4
Exercises
The subject O (n) is a lot of practice.
Procedure one:
Consider the balance of the substring must be (...) (...) (...) The structure of a method, when swept from left to right, for each left parenthesis I, tries to match a closing parenthesis pi, (if there is no match set PI is-1) the initial each left bracket is set to not be marked, the order enumeration is not tagged with a matching opening parenthesis I, mark it, and then see if the pi+1 position has a matching opening parenthesis If it is, mark it, and then repeat the operation so that a series of valid parentheses are obtained, and they do not intersect, but are connected, for example with K, and correspond to k* (k+1)/2 balanced substrings. Because each parenthesis is marked only once, the complexity is O (n).
Method Two, considering the dynamic programming F[i] represents the number of balance strings ending with the I-character, preprocessing the left parenthesis J that matches the closing parenthesis, and f[i]=f[j]+1 if present; The complexity is also O (n).
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm>using namespace std;const int Maxn=1000006;char s[maxn];int st[maxn],dp[maxn];int main () { int top=-1; Long long sum=0; scanf ("%s", s); int Len=strlen (s); for (int i=0;i<len;i++) { if (s[i] = = ' (') { st[++top]=i; } else{ if (top! =-1) { int pre=st[top]; Dp[i]=1; if (pre! = 0) dp[i]+=dp[pre-1]; top--; } } Sum+=dp[i]; } printf ("%lld", sum); return 0;}
Carp flag at the Hihocoder 20 exhibition Resort