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,
then
題目大意
給定一個括號序列,令ans[i]表示包含第i個字符的合法的字符串個數。
求
題解
對於一個合法的括號串,都可以化成這樣的形式
定義
當然,a僅對str[i]==’(‘時有效,b僅對str[i]==’)’。
於是
這樣就代表了兩種情況:
裏面的兩個匹配的括號被外面的包含在內,
後面是一個獨立的匹配括號。
對於第一種情況,a[i]當然是1,而由於match[i]+1是’)’所以
而對於第二種情況,
b的推導也與此類似。
從這個推導式可以看出來,a數組需要倒着求,b數組需要正着求。
再考慮如何求出
其中
對於這個表達式,可以這樣理解:以a開頭的合法串有
這題非常坑的一點就是這個取模是在
對於match,up這些數組,可以用一個棧來算出,值得注意的是,計算up的時候,要先判這個左括號是不是有匹配的右括號,有才會計算up再塞入棧中。
複雜度爲
#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;
}