P9089 题解
这道题目显然与字符串相关,而处理一段子串与所有的后缀库中是否有匹配的最简便方式就是哈希。因此,一个做法就是先把所有的后缀的哈希值都丢进一个集合里面,然后枚举子串尝试去和集合里面的哈希值匹配,但是,这样做,复杂度是
然而,真的有必要枚举所有的子串吗?其实没必要,原因在于假设一个非空字符串
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll N=5e5+7;
const ll B=1327;
const ll X=1321321327;//建议双哈希,否则容易寄(字符串个数约为10^6)
const ll Y=1431431437;//同时建议用生僻一点的模数,否则被针对
ll px[N*2],py[N*2];
void init(){//初始化两种模数
px[0]=py[0]=1;
for(ll i=1;i<=1e6;++i){
px[i]=px[i-1]*B%X;
py[i]=py[i-1]*B%Y;
}
}
struct H{//双哈希
ll l,x,y;
H(ll l=0,ll x=0,ll y=0):l(l),x(x),y(y){}
friend H operator +(H a,char c){//插入字符
return H(a.l+1,(a.x*B+c)%X,(a.y*B+c)%Y);
}
friend H operator -(H a,H b){//区间哈希
return H(a.l-b.l,(a.x-b.x*px[a.l-b.l]%X+X)%X,(a.y-b.y*py[a.l-b.l]%Y+Y)%Y);
}
friend bool operator <(H a,H b){
if(a.x^b.x)
return a.x<b.x;
return a.y<b.y;
}
};
ll n,tp,res;
char s[N*2];
string str[N];
set<H>st[N*2];
H stk[N*2];
int main(){
init();
scanf("%lld",&n);
for(ll i=1;i<=n;++i){
scanf("%s",s);
str[i]=s;
}
for(ll i=1;i<=n;++i){
ll pos=str[i].length();
H cur;//初始默认为空串
while(pos){//倒序枚举
--pos;
cur=cur+str[i][pos];
st[cur.l].insert(cur);
}
}
for(ll i=1;i<=n;++i){
while(tp)
stk[tp--]=H();
ll pos=str[i].length();
H cur;
tp=1;//注意初始需要加入一个空串
while(pos){
--pos;
cur=cur+str[i][pos];
while(tp&&!st[cur.l-stk[tp].l].count(cur-stk[tp]))//不满足条件,出栈
stk[tp--]=H();
res+=tp;
stk[++tp]=cur;//无论如何都要入栈一次
}
}
printf("%lld\n",res);
return 0;
}