Power Strings KMP next陣列的應用
題目:
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).
輸入:
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.
輸出:
For each s you should print the largest n such that s = a^n for some string a.
樣例輸入:
abcd aaaa ababab .
樣例輸出:
1 4 3
題意:
給出一串字串長度為len,求一個最小長度為A的迴圈體,有一個K滿足K*A=len,求這個K的最大值,也就是求這個迴圈體長度的最小值。這個題用了next陣列的應用。
有一個定理,如果一個字串的長度為len,當且僅當len%(len-net[len])==0,他的最短迴圈子串的長度是len-net[len]。
拿第三個案例來講
i 0 1 2 3 4 5 6
s[i] a b a b a b #(#是假定的,不能輸入的s的一部分)
net[i] -1 0 0 1 2 3 4
可以看到s[i]的長度len為6,net[6]=4,所以len-net[len]=2,正好是最小迴圈子串ab的長度。
AC程式碼:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn=1000005;
int len;
char s[maxn];
int net[maxn];
void getnet()
{
net[0]=-1;
int k=-1;
int j=0;
while(j<len)
{
if(k==-1||s[j]==s[k])
{
++j;
++k;
net[j]=k;
}
else
k=net[k];
}
}
int main()
{
while(scanf("%s",s)!=EOF)
{
if(s[0]=='.')break;
len=strlen(s);
getnet();
if(len%(len-net[len])==0)
{
printf("%d\n",len/(len-net[len]));
}
else
printf("1\n");//如果不能整除,就輸出1,譬如abcd這樣的情況,沒有迴圈的子串
}
return 0;
}