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
",ans);
	return 0;
}
原文地址:https://www.cnblogs.com/Hawking-llfz/p/11508984.html