POJ 2406 Power Strings(最小迴圈節的應用)
阿新 • • 發佈:2019-01-23
Power Strings
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.
Time Limit: 3000MS | Memory Limit: 65536K |
Total Submissions: 27359 | Accepted: 11450 |
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
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題目大意:給你一個串s,求a^n=s,求出最大的n.記得以前曾經暴力解過此類題目。 由於是a^n跟剪花布條類似,不能重合。 AC程式碼:
#include<iostream> #include<cstring> #include<cstdio> #include<string> using namespace std; char a[1000005]; int len,next[1000005]; void getnext() { int i,j; next[0]=0,next[1]=0; for(i=1;i<len;i++) { j=next[i]; while(j&&a[i]!=a[j]) j=next[j]; if(a[i]==a[j]) next[i+1]=j+1; else next[i+1]=0; } } int main() { while(scanf("%s",a)) { if(strcmp(".",a)==0) break; len=strlen(a); getnext(); int res; if(len%(len-next[len]))//len-next[len]為最小迴圈節 res=1; //需要排除AZAZAZA的情況,此時應該輸出1而不是3.考慮重合或者不重合 else res=len/(len-next[len]); printf("%d\n",res); } return 0; }