[KMP算法]C. 【例题3】周期长度和
解析
本题解是用KMP算法来完成此题。
Code
#include <bits/stdc++.h>
#define N 1000005
#define ll long long
using namespace std;
int k[N];
string s;
ll len, ans;
ll f (ll x)
{
if (k[x] != 0) return k[x] = f (k[x]);
return x;
}
int main ()
{
cin >> len >> s;
s = ' ' + s;
k[1] = 0;
ll i = 1, j = 0;
while (i < len)
{
while (j && s[j + 1] != s[i + 1]) j = k[j];
if (s[j + 1] == s[i + 1]) ++ j;
k[i + 1] = j;
++ i;
}
for (i = 1; i <= len; ++ i) ans += i - f (i);
printf ("%lld", ans);
return 0;
}