KMP练习

洛谷P4391 (https://www.luogu.com.cn/problem/P4391)

题目描述:

 

 思路

假设最短需要x长度的子串进行自我复制,也就是说ne[x+0]=0, ne[x+1]=1 ,ne[x+2] =2,..... 那么答案很明显就是 n - ne[n] 

AC代码
#include<bits/stdc++.h> using namespace std; const int N = 1e6+10; char a[N],b[N]; int n,m; int ne[N]; int main() { cin>>n>>a+1; for(int i=2,j=0;i<=n;i++) { while(j && a[i] != a[j+1]) j=ne[j]; if(a[i] == a[j+1]) j++; ne[i] = j; } cout<<n-ne[n]; }

 

posted @ 2020-10-22 21:26  har74  阅读(78)  评论(0)    收藏  举报