最少出现K次我们可以用Height数组的lcp来得出,而恰好出现K次,我们只要除去最少出现K+1次的lcp即可。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std; const int maxn = + ; int t1[maxn], t2[maxn], c[maxn]; bool cmp(int* r, int a, int b, int l) {
return r[a] == r[b] && r[a + l] == r[b + l];
} void da(int str[], int sa[], int Rank[], int lcp[], int n, int m) {
++n;
int i, j, p, *x = t1, *y = t2;
for (i = ; i < m; ++i) c[i] = ;
// puts("hha");
for (i = ; i < n; ++i) c[x[i] = str[i]]++;
for (i = ; i < m; ++i) c[i] += c[i - ];
for (i = n - ; i >= ; --i) sa[--c[x[i]]] = i;
for (j = ; j <= n; j <<= ) {
p = ;
for (i = n - j; i < n; ++i) y[p++] = i;
for (i = ; i < n; ++i) if (sa[i] >= j) y[p++] = sa[i] - j;
for (i = ; i < m; ++i) c[i] = ;
for (i = ; i < n; ++i) c[x[y[i]]]++; for (i = ; i < m; ++i) c[i] += c[i - ];
for (i = n - ; i >= ; --i) sa[--c[x[y[i]]]] = y[i]; swap(x, y);
p = ; x[sa[]] = ;
for (i = ; i < n; ++i) {
x[sa[i]] = cmp(y, sa[i - ], sa[i], j) ? p - : p++;
}
if (p >= n)break;
m = p;
} int k = ;
n--;
for (i = ; i <= n; ++i) Rank[sa[i]] = i;
for (i = ; i < n; ++i) {
if (k)--k;
j = sa[Rank[i] - ];
while (str[i + k] == str[j + k])++k;
lcp[Rank[i]] = k;
//cout << k << endl;
}
} int lcp[maxn], a[maxn], sa[maxn], Rank[maxn]; char s[maxn]; int d[maxn][];
int len; void rmq_init(int* A, int n) {
for (int i = ; i < n; ++i) d[i][] = A[i];
for (int j = ; ( << j) <= n; ++j)
for (int i = ; i + ( << j) - < n; ++i)
d[i][j] = min(d[i][j - ], d[i + ( << (j - ))][j - ]);
} int ASK(int l, int r) {
int k = ;
while (( << (k + )) <= r - l + )++k;
return min(d[l][k], d[r - ( << k) + ][k]);
} int ask(int l, int r) {
if (l == r) return len - sa[r]; /// l == r的话 是一个串, 返回本身的长度即可。
return ASK(l + , r); ///否则在rmq查询。
} //
int main() {
//freopen("in.txt", "r", stdin);
//freopen("outstd.txt", "w", stdout);
int T;
scanf("%d", &T);
while (T--) {
int k;
scanf("%d", &k);
scanf("%s", s);
//puts(s);
len = strlen(s);
for (int i = ; i < len; ++i) {
a[i] = s[i] - 'a' + ;
}
a[len] = ;
da(a, sa, Rank, lcp, len, );
rmq_init(lcp, len + );
long long ans = ;
if (k == )
{
for (int i = ; i <= len; i++)
{
int siz = len - sa[i];
int des = ;
if (i > ) des = max(des, ask(i - , i));
if (i < len) des = max(des, ask(i, i + ));
ans += siz - des;
}
}
else
{
for (int i = ; i+k- <= len; i++)
{
int siz = ask(i, i + k - );
int des = ;
if (i > ) des = max(des, ask(i - , i + k - ));
if (i + k <= len) des = max(des, ask(i, i + k));
ans += siz - des;
}
}
printf("%I64d\n", ans);
/*
long long ans = 0; for (int i = 1; i + k - 1 <= len; ++i) {
ans += ask(i, i + k - 1);
if (i - 1 > 0)ans -= ask(i - 1, i + k - 1); ///注意边界问题。
if (i + k <= len)ans -= ask(i, i + k);
if (i - 1 > 0 && i + k <= len)ans += ask(i - 1, i + k);
}
printf("%I64d\n", ans);*/ }
return ;
}