POJ 3261
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 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
题意 : 给定一个序列,从中选择重复次数大于k次的的最长子段,可重叠
思路:
- 这道题论文里的例题,论文给出了一些相关的证明,就是对height数组分组,重复K次,可以重复,那么也就是说只要有一组height里面的个数是大于等于k的就好了, 要求最长,二分, 求最长的len
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;
#define MAXN 20010
int s[MAXN];
int n, sa[MAXN], height[MAXN], _rank[MAXN], tmp[MAXN], top[MAXN];
void makesa()
{
int i, j, len, na;
na = (n < 256 ? 256 : n);
memset(top, 0, na*sizeof(int));
for(i = 0; i < n; i++) top[_rank[i] = s[i] & 0xff] ++;
for( i = 1; i < na; i++) top[i] += top[i - 1];
for( int i = 0; i < n; i++) sa[ --top[_rank[i]]] = i;
for( len = 1; len < n; len <<= 1)
{
for( i = 0; i < n; i++)
{
j = sa[i] - len;
if(j < 0) j += n;
tmp[ top[ _rank[j] ] ++] = j;
}
sa[ tmp[top[0] = 0] ] = j = 0;
for( i = 1; i < n; i++)
{
if(_rank[tmp[i]] != _rank[tmp[i-1]] || _rank[tmp[i] + len] != _rank[tmp[i - 1] + len])
top[++j] = i;
sa[ tmp[i] ] = j;
}
memcpy(_rank, sa, n*sizeof(int));
memcpy(sa, tmp, n*sizeof(int));
if(j >= n - 1) break;
}
}
void lcp( )
{
int i, j, k;
for( j = _rank[height[i = k = 0] = 0]; i < n - 1; i++, k++)
while(k >= 0 && s[i] != s[ sa[j - 1] + k])
height[j] = (k--), j = _rank[sa[j] + 1];
}
bool isok(int len, int kk)
{
int cnt = 1;
for( int i = 1; i <= n; i++)
{
if(height[i] >= len)
cnt++;
else cnt = 1;
if(cnt >= kk)
return true;
}
return false;
}
int Bsearch(int kk)
{
int l = 1, r = n;
int pos = 0;
while(l <= r)
{
int mid = (l + r) >> 1;
if(isok(mid, kk))
{
pos = mid;
l = mid + 1;
}
else
r = mid - 1;
}
return pos;
}
int main()
{
int k;
while(scanf("%d%d",&n, &k) != EOF)
{
for( int i = 0; i < n; i++)
scanf("%d",&s[i]);
s[n++] = 0;
makesa();
lcp();
int ans = Bsearch(k);
printf("%d\n",ans);
}
return 0;
}