poj 2406 Power Strings【KMP】,poj2406
點擊開啟題目
Power Strings
| Time Limit: 3000MS |
|
Memory Limit: 65536K |
| Total Submissions: 33548 |
|
Accepted: 13935 |
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
abcdaaaaababab.
Sample Output
143
Hint
This problem has huge input, use scanf instead of cin to avoid time limit exceed.題目翻譯意:給一個字串S長度不超過10^6,求最大的n使得S由n個相同的字串a串連而成,如:"ababab"則由n=3個"ab"串連而成,"aaaa"由n=4個"a"串連而成,"abcd"則由n=1個"abcd"串連而成。
解題思路:假設S的長度為len,則S存在迴圈子串,若且唯若,len可以被len - next[len]整除,最短迴圈子串為S[len - next[len]]
利用KMP演算法,求字串的特徵向量next,若len可以被len - next[len]整除,則最大迴圈次數n為len/(len - next[len]),否則為1
#include<cstdio>#define maxn 1000002char str[maxn];int next[maxn],len,s;void GetNext(){ int i=0,j=-1; next[0]=-1; while(str[i]){ if(j==-1||str[i]==str[j]){ ++i;++j;next[i]=j; }else j=next[j]; } len=i;}int main(){ while(scanf("%s",str)==1){ if(str[0]=='.') break; GetNext(); s=len-next[len]; if(len%s==0) printf("%d\n",len/s); else printf("1\n"); }return 0;}