标签:+= sort for cpp 公共前缀 line algo pre code
重复子串即两后缀的公共前缀,最长重复子串,等价于两后缀的最长公共前缀的最大值。问题就转化成了,求height数组中长度为K的子串中的最小值的最大值。
Code:
#include <cstdio>
#include <cstring>
#include <algorithm>
const int N = 20000 + 10;
int a[N], sa[N], rak[N], tmp[N], tax[N];
int n, m, k;
int h[N];
int q[N], qhd, qtl, p[N];
inline void Rsort() {
for (int i = 1; i <= m; ++i) tax[i] = 0;
for (int i = 1; i <= n; ++i) ++tax[rak[i]];
for (int i = 1; i <= m; ++i) tax[i] += tax[i-1];
for (int i = n; i >= 1; --i) sa[tax[rak[tmp[i]]]--] = tmp[i];
}
inline void Ssort() {
for (int i = 1; i <= n; ++i) rak[i] = a[i], tmp[i] = i;
m = 101;
Rsort();
for (int w = 1, p = 0; p < n; w <<= 1) {
p = 0;
for (int i = 1; i <= w; ++i) tmp[++p] = n - w + i;
for (int i = 1; i <= n; ++i) if (sa[i] > w) tmp[++p] = sa[i] - w;
Rsort();
for (int i = 1; i <= n; ++i) tmp[i] = rak[i];
rak[sa[1]] = 1; p = 1;
for (int i = 2; i <= n; ++i) {
rak[sa[i]] = (tmp[sa[i-1]] == tmp[sa[i]]
&& tmp[sa[i-1]+w] == tmp[sa[i]+w]) ?
p : ++p;
}
m = p;
}
for (int i = 1, k = 0; i <= n; ++i) {
while (a[i + k] == a[sa[rak[i]-1] + k]) ++k;
h[rak[i]] = k;
if (k) --k;
}
}
int main() {
scanf("%d%d", &n, &k);
if (k == 1) { printf("%d\n", n); return 0; }
for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
Ssort();
int ans = 0;
for (int i = 1; i <= n; ++i) {
while (qtl > qhd && h[i] < q[qtl-1]) qtl--;
p[qtl] = i;
q[qtl++] = h[i];
while (i - p[qhd] >= k - 1) qhd++;
ans = std::max(ans, q[qhd]);
}
printf("%d\n", ans);
return 0;
}
整体思路并不是很难,有几处需要注意的地方:一个是后缀数组的求解过程中的一些小细节,一个是最后统计答案的时候单调队列操作的处理顺序。
标签:+= sort for cpp 公共前缀 line algo pre code
原文地址:https://www.cnblogs.com/wyxwyx/p/hiho1043.html