[Ybtoj第8章例2]繰り返される部分文字列[KMP]

ここに画像の説明を挿入
ここに画像の説明を挿入
ここに画像の説明を挿入
ここに画像の説明を挿入
ここに画像の説明を挿入


問題解決のアイデア

配列ppを処理しますp、文字列の長さをnnとしますn、パターン文字列は1 11からp [n] p [n]p [ n ]ビットとパターン文字列nth− p [n] np [n]np [ n ]ビットからn番目のビットが一致します。したがって、nmod(n − p [n])= = 0 n mod(np [n])== 0の場合n m o d np [ n ] ==0、連続する部分文字列が繰り返され、長さはn − p [n] np [n]です。np [ n ]、サイクル数はn / n − p [n] n / np [n]です。n / np [ n ]


コード

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

char s[1000010];
int l,i,j,p[1000010]; 

int main(){
    
    
	scanf("%s",s+1);
	l=strlen(s+1); 
	while(s[1]!='.'||l!=1){
    
    
		i=1;j=0;
		for(int i=1;i<l;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;
		}
		if(l%(l-p[l])==0)
			printf("%d\n",l/(l-p[l]));
		else printf("1\n");
		scanf("%s",s+1);
		l=strlen(s+1); 
		memset(p,0,sizeof(p));
	}
}

おすすめ

転載: blog.csdn.net/kejin2019/article/details/114440886