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
Line 1: Two space-separated integers: N and KLines 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 timesSample Input
8 2 1 2 3 2 3 2 3 1
Sample Output
4
题解:
题目意思是让你在一个数组里面找一个子串使得它出现的次数不少于K次,求最长的长度是多少。
后缀数组+二分:利用后缀数组的height数组的性质,二分答案即可。(理解了后缀数组看到二分应该就知道怎么写了)
参考代码:
#include<iostream> #include<string.h> #include<stdio.h> #include<math.h> #include<algorithm> #include<set> using namespace std; int A[20010],ha[20010]; int sa[20010],c[20010],ra[20010],x[20010],y[20010],h[20010]; void build(int n,int m){ int i,j,p; for(i=0;i<m;i++) c[i]=0; for(i=0;i<n;i++){ x[i]=A[i]+1; c[x[i]]++; } for(i=1;i<m;i++) c[i]+=c[i-1]; for(i=0;i<n;i++) sa[--c[x[i]]]=i; for(j=1;j<n;j*=2){ p=0; for(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<m;i++) c[i]=0; for(i=0;i<n;i++) c[x[y[i]]]++; for(i=1;i<m;i++) c[i]+=c[i-1]; for(i=n-1;i>=0;i--) sa[--c[x[y[i]]]]=y[i]; swap(x,y); x[sa[0]]=0; m=1; for(i=1;i<n;i++) { if(y[sa[i]]==y[sa[i-1]]&&y[sa[i]+j]==y[sa[i-1]+j]) x[sa[i]]=m-1; else x[sa[i]]=m++; } if(m>=n) break; } } void height(int n) { int i,j,k=0; for(i=0;i<=n;i++) ra[sa[i]]=i; for(i=0;i<n;i++){ if(k) k--; j=sa[ra[i]-1]; while(A[i+k]==A[j+k]) k++; h[ra[i]]=k; } } int check(int l,int n,int k){ int sum=1,ma=-1,i; for(i=1;i<=n;i++){ if(h[i]>=l){ sum++; if(ma<sum) ma=sum; } else sum=1; } return ma>=k; } set<int>s; set<int>::iterator it; int main() { int i,n,k,m; scanf("%d%d",&n,&k); for(i=0;i<n;i++) { scanf("%d",&A[i]); s.insert(A[i]); } m=0; for(it=s.begin();it!=s.end();it++) ha[m++]=*it; for(i=0;i<n;i++) A[i]=lower_bound(ha,ha+m,A[i])-ha; A[n]=-1; build(n+1,20005); height(n); int l=1,r=20005,mid; while(l+1<r) { mid=(l+r)/2; if(check(mid,n,k)) l=mid; else r=mid; } if(check(l,n,k)) printf("%d\n",l); else printf("0\n"); return 0; }View Code