美文网首页
[kuangbin带你飞]专题十六 KMP & 扩展KMP &

[kuangbin带你飞]专题十六 KMP & 扩展KMP &

作者: jenye_ | 来源:发表于2018-08-01 15:13 被阅读0次

题目

思路

  • 求最小循环节
  • 完全循环就是周期,不能完全循环就是1

AC代码

#include<iostream>
using namespace std;
const int MAXN=10000002;

string P;
string T;

int NEXT[MAXN];
int plen,tlen;
void getNEXT(){
    NEXT[0] = -1;
    int k = -1 ;
    int j = 0 ;
    while(j<plen){
        if(k==-1||P[k]==P[j]){
            NEXT[++j] = ++k;
        }else{
            k = NEXT[k];
        }
    }
    
}

int main(){
    
    ios::sync_with_stdio(false);
    while(cin>>P&&"."!=P){
        plen=P.length();
        getNEXT();
        int length = plen - NEXT[plen];
        int ans;
        if(plen%length == 0){
            ans = plen/length;
        }else ans = 1;
        cout<<ans<<"\n";
    }       
    return 0;
} 

相关文章

网友评论

      本文标题:[kuangbin带你飞]专题十六 KMP & 扩展KMP &

      本文链接:https://www.haomeiwen.com/subject/byhrvftx.html