[POJ2406] Power Strings

来源:互联网 发布:mac磁盘工具抹掉失败 编辑:程序博客网 时间:2024/06/05 14:59

题目描述

我们定义a*b为两个字符串a和b相连接,例如a = “abc” 和b=”def”,那么a*b=”abcdef”。也可以用幂运算来表示,如a^0=”” (空串) ,a^(n+1)=a*(a^n)。


输入格式

多组测试数据,每组测试数据一行仅一个字符串s,长度不超过1000000。文件最后一行为一个小数点作为结束标志。


输出格式

每组测试数据输出一行,对于某个任意字符串a,使s=a^n成立时,n的最大值。(For each string you should print the largest n such that s = a^n for some string a.)


样例数据

样例输入

abcd
aaaa
ababab
.

样例输出

1
4
3


题目分析

KMP
如果Len% (Len-next[Len])=0,则长度为Len/ (Len-next[Len])=0,否则长度为1
为什么呢?
如图,
这里写图片描述
根据字符串红色部分相同,可认为原串从蓝色部分断开。
分析蓝色竖线的后面部分,若1~next[len]是原串的循环节,那么next[len]~len一定也是,于是next[len]可以一直延伸到白色部分结束,把白色部分吃了。
但如果白色部分存在,就说明原串不可能有循环节。
因为next[len]一定是最大的,那么所找到的循环节一定是最小的,循环节最小都不存在,原串不存在循环。


源代码

#include<algorithm>#include<iostream>#include<iomanip>#include<cstring>#include<cstdlib>#include<vector>#include<cstdio>#include<cmath>#include<queue>using namespace std;inline const int Get_Int() {    int num=0,bj=1;    char x=getchar();    while(x<'0'||x>'9') {        if(x=='-')bj=-1;        x=getchar();    }    while(x>='0'&&x<='9') {        num=num*10+x-'0';        x=getchar();    }    return num*bj;}string s;int len,Next[1000005];void Get_Next(string s) {    int i=1,j=0;    Next[1]=0;    while(i<=len)        if(j==0||s[i]==s[j])Next[++i]=++j;        else j=Next[j];}int main() {    ios::sync_with_stdio(false);    while(true) {        cin>>s;        if(s[0]=='.')break;        len=s.length();        s=' '+s;        Get_Next(s);        if(len%(len+1-Next[len+1])==0)printf("%d\n",len/(len+1-Next[len+1]));        else puts("1");    }    return 0;}

0 0
原创粉丝点击