题解 P2375 【[NOI2014]动物园】
zmx_wzx_JY · · 题解
本题的指纹hash解法
博客链接这里
作者由于只有CSPJ水平,所以根本想不出KMP或者什么自动机解法。只会hash+二分
虽然该算法复杂度为
考虑
然后我们枚举
然后考虑二分过程中如何
枚举
上文中的--可以理解为~,因为作者对markdown太不了解所以只能这么写了。
排版很丑,表述很垃圾,代码也丑,希望轻喷。
code:
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+5,mod=1e9+7,md=19260817;char c[N];int hash[N],n,pre[N],pows[N];
inline void work(int x){
if(c[x]!=c[1])return ;int l=1,r=min(x-1,n-x+1);
while(l<r){int mid=l+r+1>>1;
if((hash[x+mid-1]-(long long)hash[x-1]*(long long)pows[mid]%md+md)%md==hash[mid])l=mid;else r=mid-1;
}++pre[x];--pre[x+l];
}
signed main(){
int t;scanf("%d",&t);while(t--){
scanf("%s",c+1);n=strlen(c+1);pows[0]=1;memset(pre,0,sizeof(pre));
for(int i=1;i<=n;++i)hash[i]=(hash[i-1]*26+c[i]-'a')%md,pows[i]=pows[i-1]*26%md;
for(int i=2;i<=n;++i)work(i);for(int i=1;i<=n;++i)pre[i]+=pre[i-1];
long long ans=1;for(int i=2;i<=n;++i)ans=ans*((long long)pre[i]+1ll)%mod;
printf("%lld\n",ans);
}return 0;
}
代码中的hash就是hash值,pow[i]是26的i次方。然后pre是num的差分数组。个人认为代码很好理解。