题目做法还是比较明显的,相当于问一个串中,出现了k次的最长串的长度,这样我们可以考虑SA来确定哪些串是出现了k的——height数组的一些连续的值可以反映这一点。然后我们其实就将问题转化成了求ans =max{min(h[i]...h[i+k-2])}这样的话,我们可以预处理一个rmq来解决这个问题(这次用了树状数组)
#include<cstdio>
#include<algorithm>
#define maxn 1000100
using namespace std;
int ws[maxn],wv[maxn],a[maxn],x[maxn],y[maxn],t[maxn],sa[maxn],idx[maxn],h[maxn],n,l,ans;
void init(){
scanf("%d%d",&n,&l);
for (int i = 1 ; i <= n ; i ++) scanf("%d",&a[i]);
}
bool cmp(int *rank,int a,int b,int l){
return (rank[a] == rank[b] && rank[a+l] == rank[b+l]);
}
void da(int *x,int *y,int *t){
int i,j,p,m = maxn;
for (i = 0 ; i <= m ; i ++) ws[i] = 0;
for (i = 1 ; i <= n ; i ++) ws[x[i] = a[i]] ++;
for (i = 1 ; i <= m ; i ++) ws[i] += ws[i - 1];
for (i = n ; i >= 1 ; i --) sa[ws[x[i]] --] = i;
for (j = 1,p = 1 ; p < n ; j *= 2,m = p){
for (p = 0,i = n - j + 1 ; i <= n ; i ++) y[++ p] = i;
for (i = 1 ; i <= n ; i ++) if (sa[i] > j) y[++ p] = sa[i] - j;
for (i = 0 ; i <= m ; i ++) ws[i] = 0;
for (i = 1 ; i <= n ; i ++) wv[i] = x[y[i]];
for (i = 1 ; i <= n ; i ++) ws[wv[i]] ++;
for (i = 1 ; i <= m ; i ++) ws[i] += ws[i - 1];
for (i = n ; i >= 1 ; i --) sa[ws[wv[i]] --] = y[i];
for (t = x,x = y,y = t,p = 1,i = 2,x[sa[1]] = 1 ; i <= n ; i ++)
x[sa[i]] = cmp(y,sa[i - 1],sa[i],j) ? p : ++ p;
}
}
void calc(){
int k = 0,j,i;
for (i = 1 ; i <= n ; i ++) x[sa[i]] = i;
for (i = 1 ; i <= n ; h[x[i ++]] = k)
for (k ? k -- : 0,j = sa[x[i] - 1] ; a[i + k] == a[j + k] ; k ++);
}
int lowbit(int x){
return -x & x;
}
int Query(int l,int r){
int ans = h[r];
while(1){
ans = min(ans,h[r]);
if(r == l) break;
for(r -= 1 ; r - l >= lowbit(r) ; r -= lowbit(r)) ans = min(ans,idx[r]);
}
return ans;
}
void rmq(){
for (int i = 1 ; i <= n ; i ++) idx[i] = h[i];
for (int i = 1 ; i <= n ; i ++)
for (int j = i ; j <= n ; j += lowbit(j)) idx[j]=min(idx[j],h[i]);
}
void work(){
da(x,y,t);
calc();
rmq();
for (int i = 1 ; i <= n - (l - 2) ; i ++)ans = max(Query(i,i + l - 2),ans);
}
int main(){
init();
work();
printf("%d",ans);
}