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
题目大意就是输入字符串,以“ . ”结束,让你求出字符串中循环节的最小长度。
用 kmp 中的 x = n - nex[n-1] 计算循环节,具体看代码。
#include<stdio.h>
#include<string.h>
const int N = 1000005;
char a[N];
int nex[N],n;
void init()
{
nex[0] = 0;//nex数组的建立
int i = 1,j = 0;
while(i < n)
{
if(a[i] == a[j])
nex[i++] = ++j;
else if(!j)
i++;
else
j = nex[j-1];
}
}
int main()
{
while(~scanf("%s",a) && a[0]!='.')
{
memset(nex,0,sizeof nex);
n = strlen(a);
init();
int x = n - nex[n-1];//下面两部就是当 n % x为 0 的时候代表有循环节
if(n % x == 0)
printf("%d\n",n/x);
else printf("%d\n",1);//否则就是没有,输出1
}
return 0;
}
还有一种 nex 数组的写法,区别其实也不大,看个人习惯;
1,一个就是初始的建立不同;
2,上面的一个 nex[i] 代表 0 ~ i(包括 i )的最长前后缀,下面的 nex[i]是代表,0 ~ i - 1(包括 i - 1)的写法;
3,第一个 nex 数组下标是 0 ~n -1的,而下面的下标是 0 ~ n,就是使用的时候下标不太一样。
#include<stdio.h>
#include<string.h>
const int N = 1000005;
int nex[N],n;
char a[N];
void init()
{
int i = 0,j = -1;
nex[0] = -1;
while(i < n)
{
if(j == -1 || a[i] == a[j])
nex[++i] = ++j;
else
j = nex[j];
}
}
int main()
{
while(scanf("%s",a) && a[0] != '.')
{
memset(nex,0,sizeof nex);
n = strlen(a);
init();
int x = n - nex[n];
if(n % x == 0)
printf("%d\n",n/x);
else
printf("1\n");
}
return 0;
}