E - Power Strings
Time Limit:3000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
Submit Status Practice POJ 2406
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 讲了这么多,其实就是一个求一个字符串里最小周期的问题。限时有3S,我们可以用枚举。这里需要注意的是一个:求周期串的基本算法:for(i=1;i<=len;i++){ ok=1; if(len%i==0) { for(j=i;j<len;j++) { if(s[j]!=s[j%i]){ok=0;break;} } }if(ok==1){ printf("%d\n",len/i); break;//记得要break}}
1 #include<cstdio> 2 #include<string.h> 3 using namespace std; 4 char s[1000100]; 5 int main() 6 { 7 while(scanf("%s",s)==1&&strcmp(s,".")!=0) 8 { 9 int len=strlen(s); 10 11 for(int i=1;i<=len;i++) 12 if(len%i==0) 13 { 14 int ok=1; 15 for(int j=i;j<len;j++) 16 { 17 if(s[j]!=s[j%i]) 18 { 19 ok=0; 20 break; 21 } 22 } 23 if(ok) 24 { 25 printf("%d\n",len/i); 26 break; 27 } 28 29 } 30 } 31 return 0; 32 }
E - Power Strings,求最小周期串