E - Power Strings
Time Limit:3000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
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
}
}
#include<cstdio>
#include<string.h>
using namespace std;
char s[];
int main()
{
while(scanf("%s",s)==&&strcmp(s,".")!=)
{
int len=strlen(s); for(int i=;i<=len;i++)
if(len%i==)
{
int ok=;
for(int j=i;j<len;j++)
{
if(s[j]!=s[j%i])
{
ok=;
break;
}
}
if(ok)
{
printf("%d\n",len/i);
break;
} }
}
return ;
}