Description
定义 (A) 串为 (B) 串的循环串,当且仅当 (A) 是 (B) 的前缀(不包括 (B) 本身),且 (B) 为连续的 (A) 串拼接的字符串的前缀。给出一个长度为 (n) 字符串,求它的所有前缀(包括本身)的最长循环串的长度之和。
(1leq nleq 1000000)
Solution
容易发现最长循环串长度=总长度-最短相同前后缀长度。
(KMP) 递推时同时处理出一个 (low) 数组即可,表示最短相同前后缀长度。
Code
//It is made by Awson on 2018.3.17
#include <bits/stdc++.h>
#define LL long long
#define dob complex<double>
#define Abs(a) ((a) < 0 ? (-(a)) : (a))
#define Max(a, b) ((a) > (b) ? (a) : (b))
#define Min(a, b) ((a) < (b) ? (a) : (b))
#define Swap(a, b) ((a) ^= (b), (b) ^= (a), (a) ^= (b))
#define writeln(x) (write(x), putchar('
'))
#define lowbit(x) ((x)&(-(x)))
using namespace std;
const int N = 1e6;
void read(int &x) {
char ch; bool flag = 0;
for (ch = getchar(); !isdigit(ch) && ((flag |= (ch == '-')) || 1); ch = getchar());
for (x = 0; isdigit(ch); x = (x<<1)+(x<<3)+ch-48, ch = getchar());
x *= 1-2*flag;
}
void print(unsigned LL x) {if (x > 9) print(x/10); putchar(x%10+48); }
void write(unsigned LL x) {if (x < 0) putchar('-'); print(Abs(x)); }
int n, nxt[N+5], low[N+5]; unsigned LL ans;
char ch[N+5];
void work() {
read(n); scanf("%s", ch+1);
for (int i = 2; i <= n; i++) {
int j = nxt[i-1];
while (j && ch[j+1] != ch[i]) j = nxt[j];
if (ch[j+1] == ch[i]) nxt[i] = j+1, low[i] = (low[j+1] == 0 ? j+1 : low[j+1]);
ans += low[i] ? i-low[i] : low[i];
}
writeln(ans);
}
int main() {
work(); return 0;
}