POJ2406-Power Strings
阿新 • • 發佈:2018-12-24
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: 55320 | Accepted: 22983 |
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
Hint
This problem has huge input, use scanf instead of cin to avoid time limit exceed.題解:題意就是由一個字串重複多遍組成,求最多重複次數。
也就是求這個字串的最小長度即可。很明顯與KMP的fail陣列有關,求出可以發現如果重複次數大於1,那麼n-fail[n]必定是最小的字串長度。隨便列幾次就可以發現了。
Code:
#include<cstdio> #include<cstring> #include<algorithm> #include<iostream> using namespace std; #define N 1000005 int next[N],len; int main() { char a[N]; while(~scanf("%s",a)) { if(a[0]=='.')break; len=strlen(a); int i=0,j=-1; next[0]=-1; while(i<len) { if(j==-1||a[i]==a[j]) { i++,j++; next[i]=j; }else j=next[j]; } int k=len-next[len]; if(len%k==0)printf("%d\n",len/k); else printf("1\n"); } return 0; }