为什么 O(n2) 的哈希能过?
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int mod1=1e9+123,mod2=5e7+17;
const int base1=131,base2=61;
int pw1[1000005],pw2[1000005];
int hsh1[1000005],hsh2[1000005];
int border[1000005];
int n,len;
string s;
pair<int,int> hsh(int l,int r){
int h1=hsh1[r]-hsh1[l-1]*pw1[r-l+1]%mod1;
h1=(h1%mod1+mod1)%mod1;
int h2=hsh2[r]-hsh2[l-1]*pw2[r-l+1]%mod2;
h2=(h2%mod2+mod2)%mod2;
return {h1,h2};
}
bool same(int a,int b,int c,int d){
return hsh(a,b)==hsh(c,d);
}
int f(int x,int y){
if(x>y) swap(x,y);
if(s[x]!=s[y]) return 0;
int l=1,r=x-1,mx=x-1;
while(l<=r){
int mid=(l+r)/2;
if(same(x-mid+1,x,y-mid+1,y)){
l=mid+1;
mx=mid;
}else{
r=mid-1;
}
}
mx=min(mx,border[x]);
for(int i=mx;i>=1;i--){
if(same(1,i,x-i+1,x)&&same(1,i,y-i+1,y)){
return i;
}
}
return 0;
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>s;
len=s.length();
s="#"+s;
pw1[0]=pw2[0]=1;
int j=0;
for(int i=2;i<=len;i++){
while(j>0&&s[i]!=s[j+1]) j=border[j];
if(s[i]==s[j+1]) j++;
border[i]=j;
}
for(int i=1;i<=len;i++){
pw1[i]=pw1[i-1]*base1%mod1;
pw2[i]=pw2[i-1]*base2%mod2;
}
for(int i=1;i<=len;i++){
hsh1[i]=(hsh1[i-1]*base1+s[i])%mod1;
hsh2[i]=(hsh2[i-1]*base2+s[i])%mod2;
}
cin>>n;
while(n--){
int a,b;
cin>>a>>b;
cout<<f(a,b)<<"\n";
}
return 0;
}