Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P2852 [USACO06DEC]Milk Patterns G

P2852 [USACO06DEC]Milk Patterns G

题意求最长的至少出现了 $k$ 次的子串,$ht_i$ 表示排名为 $i$ 的子串和排名为 $i - 1$ 的子串的 LCP ,$\min _ {i = x + 1} ^ y ht[i]$ 可以表示后缀 $x$ 和后缀 $y$ 的 LCP ,也可以表示 $x$ 到 $y$ 的 LCP ,长度为 $k$ 的窗口的最小值就可以表示其中所有后缀的 LCP ,所有窗口的最大值即为答案。

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 2e4 + 10, M = 1e6 + 10;
int n, m, k, s[N], sa[N], rnk[N], ht[N], x[N], y[N], c[N];
void init()
{
for (int i = 1; i <= m; i++)
c[i] = 0;
for (int i = 1; i <= n; i++)
c[x[i] = s[i]]++;
for (int i = 1; i <= m; i++)
c[i] += c[i - 1];
for (int i = n; i; i--)
sa[c[x[i]]--] = i;
for (int k = 1; k <= n; k <<= 1)
{
int cnt = 0;
for (int i = n - k + 1; i <= n; i++)
y[++cnt] = i;
for (int i = 1; i <= n; i++)
if (sa[i] > k)
y[++cnt] = sa[i] - k;
for (int i = 1; i <= m; i++)
c[i] = 0;
for (int i = 1; i <= n; i++)
c[x[i]]++;
for (int i = 2; i <= m; i++)
c[i] += c[i - 1];
for (int i = n; i; i--)
sa[c[x[y[i]]]--] = y[i];
for (int i = 1; i <= n; i++)
y[i] = x[i];
for (int i = 1; i <= n; i++)
x[i] = 0;
x[sa[1]] = 1;
cnt = 1;
for (int i = 2; i <= n; i++)
if (y[sa[i]] == y[sa[i - 1]] && y[sa[i] + k] == y[sa[i - 1] + k])
x[sa[i]] = cnt;
else
x[sa[i]] = ++cnt;
if (cnt == n)
break;
m = cnt;
}
for (int i = 1; i <= n; i++)
rnk[sa[i]] = i;
for (int i = 1; i <= n; i++)
{
if (rnk[i] == 1)
continue;
int j = sa[rnk[i] - 1], k = max(0, ht[rnk[i - 1]] - 1);
while (i + k <= n && j + k <= n && s[i + k] == s[j + k])
k++;
ht[rnk[i]] = k;
}
}
int q[N];
int main()
{
scanf("%d%d", &n, &k);
k--;
for (int i = 1; i <= n; i++)
{
scanf("%d", &s[i]);
m = max(m, s[i]);
}
init();
int res = 0, hd = 1, tl = 0;
for (int i = 1; i <= n; i++)
{
while (hd <= tl && q[hd] + k - 1 < i)
hd++;
while (hd <= tl && ht[q[tl]] >= ht[i])
tl--;
q[++tl] = i;
if (i >= k)
res = max(res, ht[q[hd]]);
}
printf("%d", res);
return 0;
}