poj 2406 Power Strings

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

abcd
aaaa
ababab
.

Sample Output

1
4
3

Hint

This problem has huge input, use scanf instead of cin to avoid time limit exceed.
题意:自己看(最后遇到“.”要break)
解:
len为整个字符串的长度
想一想next[i]的含义
每次匹配失败后,都要回到next[i]开始重新匹配
也就是说  next[i]+1 -> len  这段字符 (令k为这段字符的长度)和
1 -> 1+k  这段字符 是相同的
OK,如果(len%(len-next[len])==0)  ==>  存在 len/(len-next[len]) 段 解
否则只有1段
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #include<cmath>
 5 #include<cstring>
 6 #include<string>
 7 #include<queue>
 8 #include<map>
 9 using namespace std;
10 const int N=1e7;
11 char s[N];
12 int len,ne[N],j;
13 int main()
14 {
15     while(scanf("%s",s+1)!=EOF)
16     {
17         if(s[1]=='.') break;
18         len=strlen(s+1);
19         for(int i=0;i<=len;++i) ne[i]=0;
20         for(int i=2;i<=len;++i)
21         {
22             j=ne[i-1];
23             while(j && s[i]!=s[j+1]) j=ne[j];
24             if(s[i]==s[j+1]) ne[i]=j+1;
25         }
26         if(len%(len-ne[len])==0) printf("%d\n",len/(len-ne[len]));
27         else printf("1\n");
28     }
29     return 0;
30 }
View Code
posted @ 2018-03-13 18:32  月亮茶  阅读(133)  评论(0编辑  收藏  举报