码迷,mamicode.com
首页 > 其他好文 > 详细

POJ2406-Power Strings-KMP循环节/哈希循环节

时间:2019-10-27 23:13:50      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:string   cas   rac   orm   test   continue   turn   连接   power   

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.

 

题意:

求每个字符串最多是由多少个相同的子字符串重复连接而成的。

如:ababab 则最多有3个 ab 连接而成。

 

思路:两种方法求循环节的模板题。

 

KMP:

 

 1 #include<stdio.h>
 2 #include<string.h>
 3 typedef unsigned long long ull;
 4 const int N=1e6+20;
 5 char a[N];
 6 ull p[N],sum[N],x=131;
 7 
 8 void init()
 9 {
10     p[0]=1;
11     for(int i=1; i<N; i++)
12         p[i]=p[i-1]*x;
13 }
14 
15 int main()
16 {
17     init();
18     while(~scanf("%s",a+1))
19     {
20         if(a[1]==.)
21             break;
22         int len=strlen(a+1);
23         sum[0]=0;
24         for(int i=1;i<=len;i++)//主串哈希值
25             sum[i]=sum[i-1]*x+a[i];
26         for(int i=1; i<=len; i++)
27         {
28             if(len%i!=0)
29                 continue;//说明不存在该循环节
30             int flag=0;
31             for(int j=i; j<=len; j+=i)
32             {   //ababab 
33                 //i=2时 -> j=2、4、6
34                 if((sum[j]-sum[j-i]*p[i])!=sum[i])
35                 //(sum[2]-sum[2-2]*p[2])!=sum[2]
36                 //(sum[4]-sum[4-2]*p[2])!=sum[2]
37                 //(sum[6]-sum[6-2]*p[2])!=sum[2]
38                 {
39                     flag=1;
40                     break;
41                 }
42             }
43             if(flag==0)
44             {
45                 printf("%d\n",len/i);
46                 break;
47             }
48         }
49     }
50     return 0;
51 }

 

 

 

 

哈希:

 

 

POJ2406-Power Strings-KMP循环节/哈希循环节

标签:string   cas   rac   orm   test   continue   turn   连接   power   

原文地址:https://www.cnblogs.com/OFSHK/p/11749335.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!