Time Limit: 5000MS

    Memory Limit: 65536K
Total Submissions: 14845   Accepted: 6612
Case Time Limit: 2000MS

Description

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 ≤ KN) 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.

Input

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.

Output

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

Sample Input

8 2
1
2
3
2
3
2
3
1

Sample Output

4

Source

题目大意:
给你一个n个在1~1000000范围的整数,求最长的且有k个可重叠相同子串。
先求后缀数组
二分答案,check的过程我们只需要根据h数组分组。
看有没有组的大小大于等于k的即可。
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=20005;
struct Z
{
    int zh,xh;
}z[N];
int to[N],sa[N],wa[N<<1],wb[N<<1],sr[N],h[N],k;
bool cmp(const Z &a,const Z &b)
{
    return a.zh!=b.zh?a.zh<b.zh:a.xh>b.xh;
}
bool sf(int a,int n)
{
    
    for(int i=1,sg=0;i<n;++i)
    {
        if(h[i]<a) sg=i;
        if(i-sg+1>=k) return 1;
    }
    return 0;
}
int main()
{
    int n,m=1,*x=wa,*y=wb;
    scanf("%d%d",&n,&k);
    for(int i=0;i<n;++i) scanf("%d",&z[i].zh),sr[i]=z[z[i].xh=i].zh;
    sort(z,z+n,cmp);
    for(int i=0;i<n;++i) sa[i]=z[i].xh;
    for(int i=1;i<n;++i)
        if(sr[sa[i]]==sr[sa[i-1]]) x[sa[i]]=m-1;
        else x[sa[i]]=m++;
    for(int j=1,p=0;m<n;j<<=1,m=p,p=0)
    {
        for(int i=n-j;i<n;++i) y[p++]=i,x[i+j]=-1;
        for(int i=0;p<n;++i) if(sa[i]>=j) y[p++]=sa[i]-j;
        for(int i=0;i<m;++i) to[i]=0;
        for(int i=0;i<n;++i) ++to[x[y[i]]];
        for(int i=1;i<m;++i) to[i]+=to[i-1];
        for(int i=n-1;i>=0;--i) sa[--to[x[y[i]]]]=y[i];
        int *t=x;x=y;y=t;
        x[sa[0]]=0;
        for(int i=p=1;i<n;++i)
            if(y[sa[i]]!=y[sa[i-1]]||y[sa[i]+j]!=y[sa[i-1]+j]) x[sa[i]]=p++;
            else x[sa[i]]=p-1;
    }
    for(int i=0,j,k=0;i<n;h[x[i++]]=k)
        if(!x[i]) k=0;
        else for(k?--k:0,j=sa[x[i]-1];i+k<n&&j+k<n&&sr[i+k]==sr[j+k];++k);
    int l=0,r=n+1;
    while(l<r-1)
    {
        int mid=r-(r-l)/2;
        if(sf(mid,n)) l=mid;
        else r=mid;
    }
    printf("%d",l);
    return 0;
}