POJ2406-Power Strings-KMP循环节/哈希循环节
Posted ofshk
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ2406-Power Strings-KMP循环节/哈希循环节相关的知识,希望对你有一定的参考价值。
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
",len/i);
46 break;
47 }
48 }
49 }
50 return 0;
51 }
哈希:
以上是关于POJ2406-Power Strings-KMP循环节/哈希循环节的主要内容,如果未能解决你的问题,请参考以下文章