You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
2.9 KiB
C++

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#define _CRT_SECURE_NO_WARNINGS
#define _SILENCE_CXX17_C_HEADER_DEPRECATION_WARNING
#include <bits/stdc++.h>
using namespace std;
#define CRP(t, x) const t &x
#define OPL(t, x) bool operator<(CRP(t, x)) const
#define FIL(x, v) memset(x, v, sizeof(x))
#define CLR(x) FIL(x, 0)
#define NE1(x) FIL(x, -1)
#define INF(x) FIL(x, 0x3f)
typedef int64_t ll, i64;
typedef uint64_t ull, u64;
const int N = 1e6 + 50;
int extend[N], nxt[N];
void exkmp(char *s, char *t)
{
int slen, tlen, a = 0, i, l, p, j;
slen = strlen(s);
tlen = strlen(t);
nxt[0] = tlen; //ÇónextÊý×é
while (a < tlen - 1 && t[a] == t[a + 1]) a++;
nxt[1] = a;
a = 1;
for (i = 2; i < tlen; i++)
{
p = a + nxt[a] - 1;
l = nxt[i - a];
if (i + l - 1 >= p)
{
j = (p - i + 1) > 0 ? p - i + 1 : 0;
while (i + j < tlen && t[i + j] == t[j]) j++;
nxt[i] = j;
a = i;
}
else
nxt[i] = l;
} //ÇóextendÊý×é
a = 0;
while (a < tlen && a < slen && t[a] == s[a]) a++;
extend[0] = a;
a = 0;
for (i = 1; i < slen; i++)
{
p = a + extend[a] - 1;
l = nxt[i - a];
if (i + l - 1 >= p)
{
j = (p - i + 1) > 0 ? p - i + 1 : 0;
while (i + j < slen && j < tlen && s[i + j] == t[j]) j++;
extend[i] = j;
a = i;
}
else
extend[i] = l;
}
}
char s[N];
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
scanf("%s", s);
exkmp(s, s);
int len = strlen(s);
ll ans = 0;
for (int i = 1; i < len; i++)
{
//printf("%2d%c", extend[i], " \n"[i == len - 1]);
ans += extend[i] + (i + extend[i] < len);
//if (i + extend[i] < len) ans++;
}
printf("%lld\n", ans);
}
return 0;
}
//int main()
//{
// char s[N];
// ull hs[N], b[N];
// for (int i = *b = 1; i < N; i++) b[i] = b[i - 1] * 131;
// int T;
// scanf("%d", &T);
// while (T--)
// {
// scanf("%s", s + 1);
// // int len = strlen(s + 1);
// // for (int i = 1; i <= len; i++) hs[i] = hs[i - 1] * 131 + s[i];
// int len = 0;
// for (char *p = s + 1; *p; len++) hs[len + 1] = hs[len] * 131 + *p++;
// ull ans = 0;
// for (int i = 2; i <= len; i++)
// {
// int L = i, R = len + 1, M = L;
// while (L < R - 1)
// {
// M = (L + R) >> 1;
// // ull hs1 = hs[M - i + 1];
// // ull hs2 = hs[M] - hs[i - 1] * b[M - i + 1];
// if (hs[M - i + 1] == hs[M] - hs[i - 1] * b[M - i + 1])
// L = M;
// else
// R = M;
// }
// ans += L - i + 1 + ((L != i || s[1] == s[L]) && L < len);
// }
// printf("%llu\n", ans);
// }
// return 0;
//}