hust 1010 The Minimum Length(循环节)【KMP】

<题目链接>

题目大意:

有一个字符串A,一次次的重写A,会得到一个新的字符串AAAAAAAA.....,现在将这个字符串从中切去一部分得到一个字符串B,例如有一个字符串A="abcdefg".,复制几次之后得到abcdefgabcdefgabcdefgabcdefg....,现在切去中间红色的部分,得到字符串B,现在只给出字符串B,求出字符串A的长度。 

解题分析:

不难发现,本题A的定义其实就是字符串中最短循环节的定义,所以直接用KMP求出B字符串中的循环节即可。

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int M =1e6+7;

char s[M];
int nxt[M];
void getnext(){
    int i=0,j=-1;
    nxt[0]=-1;
    while(s[i]){
        if(j==-1||s[i]==s[j])
            nxt[++i]=++j;
        else j=nxt[j];
    }
}
int main(){
    while(gets(s)){
        getnext();
        int len=strlen(s);
        int res=len-nxt[len];
        printf("%d\n",res);
    }
    return 0;
}

 

2018-10-02

posted @ 2018-10-02 15:40  悠悠呦~  阅读(336)  评论(0编辑  收藏  举报
浏览器标题切换
浏览器标题切换end