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=1⋅1+2⋅2+3⋅3+4⋅3+5⋅2+6⋅1=42
题目大意
给定一个括号序列,令ans[i]表示包含第i个字符的合法的字符串个数。
求
题解
对于一个合法的括号串,都可以化成这样的形式
(...)(...)(...)
.
定义
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数组需要正着求。
再考虑如何求出
ansi
,
ansi=ansmatch[i]=ansup[i]+ai∗bi
其中
upi
表示包含i的最小匹配括号的左端点的下标。
对于这个表达式,可以这样理解:以a开头的合法串有
ai
种取法,b结尾的合法串有
bi
种取法,由乘法原理,可以知道不同的取法总共
ai∗bi
种。
这题非常坑的一点就是这个取模是在
Σ
内部的,外部是不取模的,所以外面用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;
}