POJ 2406 Power Strings

来源:互联网 发布:2017年人口普查数据 编辑:程序博客网 时间:2024/06/14 11:35

Power Strings
Time Limit: 3000MS Memory Limit: 65536KTotal Submissions: 50920 Accepted: 21254

Description

Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def" then a*b = "abcdef". If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = "" (the empty string) and a^(n+1) = a*(a^n).

Input

Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.

Output

For each s you should print the largest n such that s = a^n for some string a.

Sample Input

abcdaaaaababab.

Sample Output

143

题目链接:http://poj.org/problem?id=2406

题意:输入字符串,问其中最短循环出现的次数。

解题思路:最短循环节的长度cir其实就是字符串的长度len减去最后一个字符的next值,也就是cir=len-next[len]。如果cir能够被len整除,那么循环节出现的次数就是len/cir。如果不能整除那么说明该循环节是第一次出现。

AC代码:

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int MAXN = 1e6 + 10; //最大的字符串长度 char str[MAXN];int fail[MAXN];void get_fail(int n) //失配数组 {memset(fail,0,sizeof(fail));fail[0]=0; fail[1]=0; for(int i=1;i<n;i++){int j=fail[i];while(j && str[i]!=str[j]) j=fail[j];fail[i+1]=str[i]==str[j]?j+1:0;}}void solve(){int len=strlen(str); //字符串的长度 get_fail(len); //得到失陪数组 int cir=len-fail[len]; //最短的循环节长度 if(len%cir!=0) printf("1\n"); //第一次出现 else printf("%d\n",len/cir); //出现次数 }int main(void){while(gets(str)) //输入字符串 {if(str[0]=='.') break; //不满足要求,退出循环 solve(); //处理函数 }return 0;}


原创粉丝点击