迷思 2018-02-09
后缀排序
求出height之后一段区间[l,r]内,出现r-l+1次最长的串是\(min(height[i]) l<=i<=r\)
单调队列维护
代码
// luogu-judger-enable-o2 #include<cstdio> #include<cstring> #include<algorithm> const int maxn = 600007; int n,m,k; char c[maxn]; int s[maxn],height[maxn],rank[maxn],sa[maxn],saf[maxn],cnt[maxn]; void rsort() { for(int i=0;i<=m;++i) cnt[i]=0; for(int i=1;i<=n;++i) cnt[rank[saf[i]]]++; for(int i=1;i<=m;++i) cnt[i]+=cnt[i-1]; for(int i=n;i>=1;--i) sa[cnt[rank[saf[i]]]--]=saf[i]; } bool cmp(int *f,int x,int y,int w) { return f[x]==f[y]&&f[x+w]==f[y+w]; } void get_sa() { for(int i=1;i<=n;++i)rank[i]=s[i],saf[i]=i;m=127;rsort(); for(int p=1,w=1,i;p<n;w<<=1,m=p) { for(i=n-w+1,p=0;i<=n;++i)saf[++p]=i; for(i=1;i<=n;++i)if(sa[i]>w)saf[++p]=sa[i]-w; rsort();std::swap(rank,saf);rank[sa[1]]=p=1; for(i=2;i<=n;++i)rank[sa[i]]=cmp(saf,sa[i],sa[i-1],w)?p:++p; } int j,k_=0; for(int i=1;i<=n;height[rank[i++]]=k_) for(k_=k_?k_-1:k_,j=sa[rank[i]-1];s[i+k_]==s[j+k_];++k_); } void init() { scanf("%d%d",&n,&k); for(int i=1;i<=n;++i)scanf("%d",s+i); } int q[maxn]; void solve() { int h=1,t=0; k--; int ans=-1;height[1]=1; for(int i=2;i<=k;++i) { while(h<=t&&height[q[t]]>height[i])t--; q[++t]=i; } ans=std::max(ans,height[q[h]]); for(int i=k+1;i<=n;++i) { while(h<=t&&q[h]<i-k+1)h++; while(h<=t&&height[q[t]]>height[i])t--; q[++t]=i; ans=std::max(ans,height[q[h]]); } printf("%d\n",ans); } int main() { init(); get_sa(); solve(); return 0; }