Luogu P2852 [USACO06DEC]牛奶模式Milk Patterns

题意:求出现次数 \(\geq K\) 的最长子串的长度。

\(SA\) 中所有 \(i\in [l,l+K-2],ht[i]\) 的最小值。单调队列。

#include<iostream>
#include<cstdio>
#include<cstring>
#define R register int
using namespace std;
namespace Luitaryi {
inline int g() { R x=0,f=1;
  register char s; while(!isdigit(s=getchar())) f=s=='-'?-1:f;
  do x=x*10+(s^48); while(isdigit(s=getchar())); return x*f;
} const int N=100010; 
int n,m,k,ans,s[N],sa[N],rk[N],c[N],x[N],y[N],ht[N],q[N],h,t;
inline void get_sa() {
  m=122;
  for(R i=1;i<=n;++i) ++c[x[i]=s[i]];
  for(R i=1;i<=m;++i) c[i]+=c[i-1];
  for(R i=n;i;--i) sa[c[x[i]]--]=i;
  for(R t=1,top=0;top<n;m=top,t<<=1) {
    top=0;
    for(R i=n-t+1;i<=n;++i) y[++top]=i;
    for(R i=1;i<=n;++i) if(sa[i]>t) y[++top]=sa[i]-t;
    memset(c,0,(m+1)<<2);
    for(R i=1;i<=n;++i) ++c[x[i]];
    for(R i=1;i<=m;++i) c[i]+=c[i-1];
    for(R i=n;i;--i) sa[c[x[y[i]]]--]=y[i];
    swap(x,y),x[sa[1]]=top=1;
    for(R i=2;i<=n;++i) 
      x[sa[i]]=(y[sa[i]]==y[sa[i-1]]&&y[sa[i]+t]==y[sa[i-1]+t])?top:++top;
  } for(R i=1;i<=n;++i) rk[sa[i]]=i;
}
inline void get_ht() {
  R k=0;
  for(R i=1,j;i<=n;++i) {
    if(k) --k; j=sa[rk[i]-1];
    while(s[j+k]==s[i+k]) ++k;
    ht[rk[i]]=k;
  }
}
inline void main() {
  n=g(),k=g();
  for(R i=1;i<=n;++i) s[i]=g();
  get_sa(),get_ht();
  h=1,t=0;
  for(R i=1;i<=n;++i) {
    while(h<=t && q[h]<=i-k+1) ++h;
    while(h<=t && ht[q[t]]>=ht[i]) --t;
    q[++t]=i;
    if(h<=t && i>=k-1) ans=max(ans,ht[q[h]]); 
  } printf("%d\n",ans);
}
} signed main() {Luitaryi::main(); return 0;}

\(SAM\) 建出来后,跑一边子树和即为出现次数顺便记下答案。


2020.01.09

posted @ 2020-01-10 17:39  LuitaryiJack  阅读(102)  评论(0编辑  收藏  举报