kuangbin专题十六 KMP&&扩展KMP POJ2406 Power Strings

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.
 
 
prekmp写残了,导致以为EOF不会写,后来才发现Next[j]=-1了。。。。
其实就是求最小循环节,然后循环次数n就最大了。
 
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<iostream>
 4 #include<string>
 5 using namespace std;
 6 int Next[1000010],n;
 7 char p[1000010];
 8 
 9 void prekmp() {
10     int i,j;
11     j=Next[0]=-1;
12     i=0;
13     while(i<n) {
14         while(j!=-1&&p[i]!=p[j]) j=Next[j];
15         if(p[++i]==p[++j]) Next[i]=Next[j];
16         else Next[i]=j;
17     }
18 }
19 
20 int main() {
21     //freopen("in","r",stdin);
22     while(~scanf("%s",p)) {
23         if(p[0]=='.') break;
24         n=strlen(p);
25         prekmp();
26         int l=n-Next[n];
27         if(n%l==0) printf("%d\n",n/l);
28         else printf("%d\n",1);
29     }
30 }

 

posted @ 2019-01-14 15:39  Frontierone  阅读(181)  评论(0编辑  收藏  举报