POJ—2406—kmp(迴圈節1)
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;
}