题目描述

Farmer John has noticed that the quality of milk given by his cows varies from day to day. On further investigation, he discovered that although he can't predict the quality of milk from one day to the next, there are some regular patterns in the daily milk quality.
To perform a rigorous study, he has invented a complex classification scheme by which each milk sample is recorded as an integer between 0 and 1,000,000 inclusive, and has recorded data from a single cow over N (1 ≤ N ≤ 20,000) days. He wishes to find the longest pattern of samples which repeats identically at least K (2 ≤ K ≤ N) times. This may include overlapping patterns -- 1 2 3 2 3 2 3 1 repeats 2 3 2 3 twice, for example.
Help Farmer John by finding the longest repeating subsequence in the sequence of samples. It is guaranteed that at least one subsequence is repeated at least K times.

输入描述:

Line 1: Two space-separated integers: N and K
Lines 2..N+1: N integers, one per line, the quality of the milk on day i appears on the ith line.

输出描述:

Line 1: One integer, the length of the longest pattern which occurs at least K times

示例1

输入

8 2
1
2
3
2
3
2
3
1

输出

4

解答

这个题意是求 可重叠的出现K次的最长重复子串

我们考虑二分子串长度
#include <iostream>
#include <cstdio>
using namespace std;
const int N=200020;

int n,k,m,sa[N],h[N],rk[N],x[N],y[N],c[N],s[N];

void qsort() {
	for(int i=0;i<=m;++i) c[i]=0;
	for(int i=1;i<=n;++i) ++c[x[i]];
	for(int i=1;i<=m;++i) c[i]+=c[i-1];
	for(int i=n;i>=1;--i) sa[c[x[y[i]]]--]=y[i];
}
void get_sa() {
	for(int i=1;i<=n;++i) x[i]=s[i],y[i]=i;
	qsort();
	for(int k=1,num;num!=n;k<<=1,m=num) {
		num=0;
		for(int i=n-k+1;i<=n;++i) y[++num]=i;
		for(int i=1;i<=n;++i) if(sa[i]>k) y[++num]=sa[i]-k;
		qsort();
		swap(x,y),num=0;
		for(int i=1; i<=n; ++i)
        	x[sa[i]]=(y[sa[i]]==y[sa[i-1]])&&(y[sa[i]+k]==y[sa[i-1]+k])?num:++num; 
	}
	for(int i=1;i<=n;++i) rk[sa[i]]=i;
}
void get_height() {
	int k=0;
	for(int i=1;i<=n;++i) {
		if(rk[i]==1) continue;
		if(k) --k;
		int j=sa[rk[i]-1];
		while(i+k<=n&&j+k<=n&s[i+k]==s[j+k]) 
			++k;
//		cout<<k<<" "<<rk[i]<<endl;
		h[rk[i]]=k;
	}
}

bool check(int x) {
	int cnt=1;
	for(int i=2;i<=n;++i) {
		if(h[i]<x) cnt=1;
		else cnt++;
		if(cnt>=k) return 1; 
	}
	return 0;
}
inline int read() {
    int s=0;
    char ch=getchar();
    while(ch<'0'||ch>'9') ch=getchar();
    while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
    return s;
}
int main() {
//	freopen("1.txt","r",stdin);
	n=read(),k=read();
	m=2000;
	for(int i=1;i<=n;++i) s[i]=read();
	get_sa(),get_height(); 
	int l=1,r=n,mid,ans=0;
	while(mid=(l+r)>>1,l^r) {
		if(check(mid+1)) ans=l=mid+1;
		else r=mid;
	}
	cout<<ans<<endl;
		
	return 0;
}

来源:子衿君