哈希表
#include<cstdio> #include<iostream> #include<queue> #include<algorithm> #define P1 20031101 #define P2 998244353 #define N 1000000 #define int long long using namespace std; int head[30000000],nxt[N],to[N]; int l[N],h1[N],h2[N],pw1[N],pw2[N]; char s[N]; int n,cnt,p=97; int read() { int x=0,f=1; char ch=getchar(); while(ch<'0'||ch>'9') { if(ch=='-') f=-1; ch=getchar(); } while(ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar(); return x*f; } void init() { pw1[0]=pw2[0]=1; for(int i=1; i<=n; i++) { h1[i]=(h1[i-1]*p+s[i])%P1; pw1[i]=pw1[i-1]*p%P1; h2[i]=(h2[i-1]*p+s[i])%P2; pw2[i]=pw2[i-1]*p%P2; } } void clear() { for(int i=1; i<=cnt; i++) head[l[i]]=0; cnt=0; } bool find(int x,int y) { for(int i=head[x]; i; i=nxt[i]) if(to[i]==y) return 1; l[++cnt]=x; to[cnt]=y; nxt[cnt]=head[x]; head[x]=cnt; return 0; } bool check(int x) { if(x==0) return 1; clear(); for(int i=1; i<=n-x+1; i++) if(find((P1+h1[i+x-1]-h1[i-1]*pw1[x]%P1)%P1,(P2+h2[i+x-1]-h2[i-1]*pw2[x])%P2)) return 1; return 0; } void solve() { int L=0,R=n; int ans=-1; while(L<=R) { int mid=(L+R)>>1; if(check(mid)) ans=mid,L=mid+1; else R=mid-1; } printf("%lld\n",ans); } main() { n=read(); scanf("%s",s+1); init(); solve(); return 0; }