Luogu P3435 [POI2006]OKR-Periods of Words


Luogu P3435 [POI2006]OKR-Periods of Words

解析

  • KMP 中 next 数组的神奇应用

Code

#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define LL long long
using namespace std;
const int N=1e6+5;
int k,p[N];
char a[N];
LL ans;
void kmp()
{
	int j=0;
	for(int i=1;i<k;i++)
	{
		while(j>0&&a[i+1]!=a[j+1]) j=p[j];
		if(a[i+1]==a[j+1]) j++;
		p[i+1]=j;
		if(p[p[i+1]]!=0) p[i+1]=p[p[i+1]];
	}
	return;
}
int main()
{
	scanf("%d",&k);
	cin>>(a+1);
	kmp();
	for(int i=1;i<=k;i++) if(p[i]) ans+=i-p[i];
	printf("%lld\n",ans);
	return 0;
}
posted @ 2019-09-11 21:38  Hawking_llfz  阅读(114)  评论(0编辑  收藏  举报