kmp例题

 原题:2406 -- Power Strings

题解:找最短循环节,定义:nxt[i] 为 1-i的最长相同前后缀长度,循环节长度为n-nxt[n]

//#include<bits/stdc++.h>
#include<cstdio>
#include<cstring>
#define reg register
using namespace std;
const int N=1e6+10;
char str[N];
int nxt[N],n;
int main(){
//	freopen("poj2406.in","r",stdin);
	while(1){
		scanf("%s",str+1);
		if(str[1] == '.')break;
		n=strlen(str+1);
		nxt[0]=-1;
		for(reg int i=1,j;i<=n;i++){
			j=nxt[i-1];
			while(j!=-1 && str[i]!=str[j+1]) j=nxt[j];
			nxt[i]=++j;
		}
		int t=n-nxt[n];
		if(n%t==0)printf("%d\n",n/t);
		else printf("1\n");	
	}
	return 0;
}

  


Kmp 模板

#include<bits/stdc++.h>
#define pa pair<int,int>
using namespace std;
typedef long long ll;
const int N = 2e5+10;
int cas,n;

int a[N],b[N];
int nxt[N];
string s,t;
int main(){
	cin>>s>>t;
	int  n = t.size();int m = s.size();
	int  j = 0, i = 1;
	nxt[0] = 0;
	while(i < n){
		if(t[i] == t[j]){
			nxt[i] = j + 1;
			++j;
			++i;
		}else if(j > 0){
			j = nxt[j - 1];
		}else {
			++i;
		}
	}
	
    i = 0, j = 0;
    while (i < m) {
        if (s[i] == t[j]) {
            if (j == n - 1) {
            	cout<<i - j + 1<<endl;
			}
            ++i;
            ++j;
        } else if (j > 0) {
            j = nxt[j - 1]; 
        } else {
            ++i; 
        }
    }
	
	for(int i = 0;i<n;i++) cout<<nxt[i]<<" ";cout<<endl;


	return 0;
}



 

  


posted @ 2018-11-30 21:14  Exception2017  阅读(152)  评论(0编辑  收藏  举报