Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 14314 | Accepted: 6344 | |
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 ≤ 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 Ktimes.
Input
Lines 2.. N+1: N integers, one per line, the quality of the milk on day i appears on the ith line.
Output
Sample Input
8 2 1 2 3 2 3 2 3 1
Sample Output
4
Analysis
就是让你找最少出现了k次的最长子串。
显然用后缀数组预处理,然后先二分串长、再分组。
复杂度O(NlogN)
Code
//poj3261 Milk Patterns 后缀数组
#include <cstdio>
#define maxn 1000005
using namespace std;
int a[maxn], wa[maxn], wb[maxn], sa[maxn], rank[maxn], height[maxn],
ws[maxn], wv[maxn], N, K;
bool cmp(int *r, int a, int b, int l)
{return r[a]==r[b] and r[a+l]==r[b+l];}
void init(int *r, int *sa, int n, int m)
{
int i, j, p, *x=wa, *y=wb, *t, k=0;
for(i=0;i<m;i++)ws[i]=0;
for(i=0;i<n;i++)ws[x[i]=r[i]]++;
for(i=1;i<m;i++)ws[i]+=ws[i-1];
for(i=n-1;i>=0;i--)sa[--ws[x[i]]]=i;
for(j=1,p=1;p<n;m=p,j<<=1)
{
for(p=0,i=n-j;i<n;i++)y[p++]=i;
for(i=0;i<n;i++)if(sa[i]>=j)y[p++]=sa[i]-j;
for(i=0;i<n;i++)wv[i]=x[y[i]];
for(i=0;i<m;i++)ws[i]=0;
for(i=0;i<n;i++)ws[wv[i]]++;
for(i=1;i<m;i++)ws[i]+=ws[i-1];
for(i=n-1;i>=0;i--)sa[--ws[wv[i]]]=y[i];
for(t=x,x=y,y=t,p=1,x[sa[0]]=0,i=1;i<n;i++)
x[sa[i]]=cmp(y,sa[i-1],sa[i],j)?p-1:p++;
}
for(i=1;i<n;i++)rank[sa[i]]=i;
for(i=0;i<n-1;height[rank[i++]]=k)
for(k?k--:0,j=sa[rank[i]-1];r[i+k]==r[j+k];k++);
}
bool check(int l)
{
int pre, i, j;
for(pre=1,i=1;i<=N;i++)
{
if(height[i]<l)pre=i;
if(i-pre+1>=K)return true;
}
return false;
}
int main()
{
int l, r, i, mid;
scanf("%d%d",&N,&K);
for(i=0;i<N;i++)scanf("%d",a+i);
init(a,sa,N+1,1000001);
l=1,r=1000000,mid=(l+r+1)>>1;
while(l<r)
{
if(check(mid))l=mid;
else r=mid-1;
mid=(l+r+1)>>1;
}
printf("%d\n",l);
return 0;
}