[JSOI2013] 编程作业
do_it_tomorrow · · 题解
考虑一种不用 kmp 的写法。
对于大写字母,维护起来是容易的,我们直接维护。对于小写字母的位置,我们直接留空子就行了。
那么,对于小写字母,我们关注的只有一样字母之间的相对位置,那么我们对于每一个小写字母都维护一个类似于大写字母的哈希。
对于一个区间,我们把在这
这样我们就只看重相对位置,于是判断是否相同就行了。
这样的时间复杂度是
那么我们把哈希的值对随便一个值取模然后把快速幂的
#include<iostream>
#include<cstring>
using ll=unsigned long long;
using namespace std;
const int N=1e6+500;
const ll p1=113;
int n,m;
char a[N],b[N];
ll h[N][27],pw[N];
ll get(int x,int y,int k){return h[y][k]-h[x-1][k]*pw[y-x+1];}
ll ask(int x,int y){ll s=0;for(int i=0;i<27;i++) s+=pw[get(x,y,i)%1000007];return s;}
void solve(){
cin>>a+1>>b+1;
n=strlen(a+1);
m=strlen(b+1);
for(int i=1;i<=m;i++){
for(int j=0;j<27;j++) h[i][j]=h[i-1][j]*p1;
if('A'<=b[i]&&b[i]<='Z') h[i][0]+=b[i];
else h[i][b[i]-'a'+1]++;
}
ll f=ask(1,m),ans=0;
for(int i=1;i<=n;i++){
for(int j=0;j<27;j++) h[i][j]=h[i-1][j]*p1;
if('A'<=a[i]&&a[i]<='Z') h[i][0]+=a[i];
else h[i][a[i]-'a'+1]++;
}
for(int i=1;i+m-1<=n;i++){
int j=i+m-1;
if(ask(i,j)==f) ans++;
}
cout<<ans<<'\n';
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(nullptr),pw[0]=1;
for(int i=1;i<N;i++) pw[i]=pw[i-1]*p1;
int T;cin>>T;
while(T--) solve();
return 0;
}