bitset 做法。
看完本题后,可能会想到一道类似的题([NOI2023] 字符串)。这道题有 bitset 做法,本题我们也可以考虑 bitset。
我们用 来表示 是否成立。发现 满足:
由于 只能取 或 ,我们将 看成一个 bitset,将 看成这个 bitset 的第 位。我们根据上面的式子可以求出所有的 ,处理方法如下:
-
假设我们已经求出了 ,令 。
-
将 左移一位(然后需要处理边界:令 )。
-
将 的所有 的位设为 ,将所有 的位设为 。
这些都可以用 bitset 维护。为了计算第三步,我们进行预处理:对字符集中的每个字母 开一个 bitset,记为 。预处理出 的哪些位置的字母大于等于 ,并将 的这些位的值设为 。第三步操作相当于 。
然后因为我们的 是从 递推过来的,所以我们要先计算出 。使用简单的哈希+二分就可以在 的时间内算出两个字符串的最长公共前缀,进而可以算出它们的大小关系。所以我们可以在 的时间内求出 ,然后可以在 的时间内求出每个 。
由于空间原因,我们不能开 个 bitset。我们从 递推至 时,直接对 在原地做修改即可。
根据定义,答案即为所有 的 的个数总和。求出每个 后将其 的个数加入答案即可。
代码如下,可以通过(AC 记录)。
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ul;
typedef long long ll;
const int N=200005,M=400005;
ul hp[N<<1];
struct nd{
int m;
string c;
vector<ul> hs;
void gen(){
m=c.length();
c="*"+c;
hs.resize(m+2,0);
for(int i=1;i<=m;i++){
hs[i]=hs[i-1]+hp[i]*c[i];
}
}
}s,t;
int n;
bitset<N> g[26],b;
ll ans;
ul get_hs(nd &x,int l,int r){
return (x.hs[r]-x.hs[l-1])*hp[M-r];
}
int get_lc(nd &a,nd &b,int la,int lb){
int le=0,ri=n,mid;
while(le<ri){
mid=(le+ri+1)>>1;
if(get_hs(a,la,la+mid-1)==get_hs(b,lb,lb+mid-1)){
le=mid;
}
else{
ri=mid-1;
}
}
return le;
}
signed main(){
ios::sync_with_stdio(0);
hp[0]=1;
hp[1]=1e9+7;
for(int i=2;i<M;i++){
hp[i]=hp[i-1]*hp[1];
}
cin>>n;
cin>>s.c;
s.c=s.c+s.c;
cin>>t.c;
t.c=t.c+t.c;
s.gen();
t.gen();
for(int i=1;i<=n;i++){
int w=t.c[i]-'a';
g[w][i]=1;
}
for(int i=24;i>=0;i--){
g[i]|=g[i+1];
}
for(int i=1;i<=n;i++){
int w=get_lc(s,t,n,i);
if(w==n){
b[i]=1;
}
else{
int sp=n+w;
int tp=i+w;
if(s.c[sp]<t.c[tp]) b[i]=1;
}
}
ans+=b.count();
for(int i=n-1;i>=1;i--){
b>>=1;
b[n]=b[0];
b[0]=0;
int w=s.c[i]-'a';
if(w<25) b|=g[w+1];
b&=g[w];
ans+=b.count();
}
cout<<ans<<"\n";
}