选自《后缀数组--处理字符串的有力工具》
题目大意:给出字符串长度n,还有可重复子串至少出现k次。求这个重复子串的最长长度。
解题思路:和poj1743差不多,不同的是二分时,判断一个组的后缀子串个数是否小于k
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 20010;
const int maxm = 1000010;
int n, k;
int sa[maxn], str[maxn], wx[maxn], wy[maxn], c[maxm], height[maxn], rank[maxn];
inline bool cmp(int *s, int a, int b, int l);
void suffix(int *s, int *sa, int n, int m);
void cal_height(int *s, int *sa, int n);
bool check(int index, int n);
int main()
{
while(scanf("%d %d", &n, &k) != EOF)
{
for(int i = 0; i < n; i++)
{
scanf("%d", &str[i]);
str[i]++;
}
str[n] = 0;
suffix(str, sa, n + 1, maxm);
cal_height(str, sa, n);
int l = 1, r = n, ans = -1;
while(l <= r)
{
int mid = (l + r) >> 1;
if(check(mid, n + 1))
{
ans = mid;
l = mid + 1;
}
else
r = mid - 1;
}
printf("%d\n", ans);
}
return 0;
}
inline bool cmp(int *s, int a, int b, int l)
{
return s[a] == s[b] && s[a + l] == s[b + l];
}
void suffix(int *s, int *sa, int n, int m)
{
int *x = wx;
int *y = wy;
int *t, index;
for(int i = 0; i < m; i++)
c[i] = 0;
for(int i = 0; i < n; i++)
c[x[i] = s[i]]++;
for(int i = 1; i < m; i++)
c[i] += c[i-1];
for(int i = n - 1; i >= 0; i--)
sa[--c[s[i]]] = i;
for(int j = 1; j <= n; j *= 2, m = index)
{
index = 0;
for(int i = n - j; i < n; i++)
y[index++] = i;
for(int i = 0; i < n; i++)
{
if(sa[i] >= j)
y[index++] = sa[i] - j;
}
for(int i = 0; i < m; i++)
c[i] = 0;
for(int i = 0; i < n; i++)
c[x[y[i]]]++;
for(int i = 1; i < m; i++)
c[i] += c[i-1];
for(int i = n - 1; i >= 0; i--)
sa[--c[x[y[i]]]] = y[i];
t = x; x = y; y = t;
x[sa[0]] = rank[sa[0]]= 0;
index = 1;
for(int i = 1; i < n; i++)
{
if(j * 2 < n)
x[sa[i]] = cmp(y, sa[i - 1], sa[i], j) ? index - 1 : index++;
else
rank[sa[i]] = cmp(y, sa[i - 1], sa[i], j) ? index - 1 : index++;
}
}
}
void cal_height(int *s, int *sa, int n)
{
int k = 0;
for(int i = 0; i < n; height[rank[i++]] = k)
{
if(k != 0)
k--;
for(int j = sa[rank[i] - 1]; s[i + k] == s[j + k]; k++);
}
}
bool check(int index, int n)
{
int ans = 1;
for(int i = 2; i <= n; i++)
{
if(height[i] >= index)
{
ans++;
if(ans >= k)
return true;
}
else
ans = 1;
}
return false;
}