1. 程式人生 > >kuangbin專題十六 KMP&&擴充套件KMP POJ2406 Power Strings

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 }