Multi-University 2015 #6 E(hdu 5357 Easy Sequence)

題目鏈接

E - Easy Sequence

Time Limit:1000MS Memory Limit:131072KB

Description

soda has a string containing only two characters – ‘(’ and ‘)’. For every character in the string, soda wants to know the number of valid substrings which contain that character.
Note:
An empty string is valid. If S is valid, (S) is valid. If U,V are valid, UV is valid.

Input

There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:
A string s consisting of ‘(’ or ‘)’ (1≤|s|≤106).

Output

For each test case, output an integer m=∑i=1|s|(i⋅ansi mod 1000000007), where ansi is the number of valid substrings which contain i-th character.

Sample Input

2
()()
((()))

Sample Output

20
42

Hint

For the second case, ans={1,2,3,3,2,1} ,
then m=11+22+33+43+52+61=42

題目大意

給定一個括號序列,令ans[i]表示包含第i個字符的合法的字符串個數。

i=1|s|(iansi mod 1000000007)

題解

對於一個合法的括號串,都可以化成這樣的形式(...)(...)(...) .
定義ai 表示從i開始的合法字符串的個數,bi 表示以i爲結尾的合法字符串的個數。
當然,a僅對str[i]==’(‘時有效,b僅對str[i]==’)’。
於是ai=amatch[i]+1+1 ,對於這個表達式,可以這樣理解:一個左括號,它的匹配的右邊只能有兩種情況:左括號,右括號。
這樣就代表了兩種情況:
裏面的兩個匹配的括號被外面的包含在內,((...))
後面是一個獨立的匹配括號。(...)(...)
對於第一種情況,a[i]當然是1,而由於match[i]+1是’)’所以amatch[i]+1 肯定爲零。
而對於第二種情況,ai 就是在amatch[i]+1 的基礎上再加上自己這個。
b的推導也與此類似。
從這個推導式可以看出來,a數組需要倒着求,b數組需要正着求。
再考慮如何求出ansiansi=ansmatch[i]=ansup[i]+aibi
其中upi 表示包含i的最小匹配括號的左端點的下標。
對於這個表達式,可以這樣理解:以a開頭的合法串有ai 種取法,b結尾的合法串有bi 種取法,由乘法原理,可以知道不同的取法總共aibi 種。
這題非常坑的一點就是這個取模是在Σ 內部的,外部是不取模的,所以外面用long long存。
對於match,up這些數組,可以用一個棧來算出,值得注意的是,計算up的時候,要先判這個左括號是不是有匹配的右括號,有才會計算up再塞入棧中。
複雜度爲O(n)

#include<cstdio>
#include<cstring>
const int M=1000005;
const int mod=1e9+7;
typedef long long ll;
int match[M],stk[M],up[M],a[M],b[M],ans[M];
char str[M];
void solve(){
    scanf("%s",str+1);
    int len=strlen(str+1),top=0;
    for(int i=0;i<=len+1;i++)
        up[i]=a[i]=b[i]=ans[i]=match[i]=0;
    for(int i=1;i<=len;i++){
        if(str[i]=='('){
            stk[++top]=i;
        }else if(top){
            match[match[stk[top]]=i]=stk[top];
            top--;
        }
    }
    for(int i=len;i>=1;i--)
        if(str[i]=='('&&match[i]) a[i]=a[match[i]+1]+1;
    for(int i=1;i<=len;i++)
        if(str[i]==')'&&match[i]) b[i]=b[match[i]-1]+1;
    top=0;
    for(int i=1;i<=len;i++){
        if(str[i]=='('&&match[i]){
            while(top&&match[stk[top]]<match[i]) top--;
            up[i]=stk[top];
            stk[++top]=i;
        }
    }
    for(int i=1;i<=len;i++)
        if(str[i]=='(') ans[i]=ans[match[i]]=(ans[up[i]]+a[i]*1LL*b[match[i]])%mod;
    ll sum=0;
    for(int i=1;i<=len;i++)
        sum=sum+1LL*i*ans[i]%mod;
    printf("%lld\n",sum);
}
int main(){
    int cas;
    scanf("%d",&cas);
    while(cas--) solve();
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章