[2406]Power Strings (POJ) KMP
|
||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts |
Current Contest Past Contests Scheduled Contests Award Contest |
|||||||||
|
Language:
Power Strings
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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char a[1000010],b[1000010];
int next[1000010];
int n,num=1;
void get_next()//求next数组
{
int len=strlen(a);
int i=0,j=-1;
next[0]=-1;
while(i<len)
{
if(j==-1||a[i]==a[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
int main()
{
while(gets(a))
{
if(a[0]=='.')
break;
int len=strlen(a);
get_next();
int n=len-next[len];//n为循环节的长度
if(len%n==0)
printf("%d\n",len/n);
else
printf("1\n");
}
return 0;
}
|
×



浙公网安备 33010602011771号