[Ybtoj Chapter 8 Example 3] Period length and [KMP]

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here


Problem-solving ideas

Push it by hand and find that if the prefix has a common prefix and suffix of length j, then it has a period of length ij.
jjj can passKMP KMPK M P is obtained, the longest period isjjj is the smallest.


Code

#include<iostream>
#include<cstdio>
#include<iomanip>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;

char s[1000010];
long long ans,n,i,j,p[1000010];

int find(int x){
    
    //查询最小的j
	if(p[x])
		return p[x]=find(p[x]);
	else return x;
}

int main(){
    
    
	scanf("%lld",&n);
	scanf("%s",s+1);
	j=0;
	for(i=1;i<n;i++)
	{
    
    	
		while(j>0&&s[i+1]!=s[j+1])
			j=p[j];
		if(s[i+1]==s[j+1])
			j++;
		p[i+1]=j;
	}
	for(int i=1;i<=n;i++)//统计答案
		ans+=i-find(i);
	printf("%lld",ans);
} 

Guess you like

Origin blog.csdn.net/kejin2019/article/details/114676406