2012-02-22 07:19:35Morris
[UVA] 10298 - Power Strings
Problem D: 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).Each test case is a line of input representing s, a string of printable characters. For each s you should print the largest n such that s = a^n for some string a. 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.
Sample Input
abcd aaaa ababab .
Output for Sample Input
1 4 3
做法 : KMP
#include<stdio.h>
#include<string.h>
#define MaxL 10000001
int KMP_init(char *B) {
int i, j;
int P[MaxL];
P[0] = -1, i = 1, j = -1;
while(B[i]) {
while(j >= 0 && B[j+1] != B[i])
j = P[j];
if(B[j+1] == B[i])
++j;
P[i] = j, ++i;
}
return j;
}
main() {
char s[MaxL];
while(gets(s)) {
if(s[0] == '.' && s[1] == '\0')
break;
int n = strlen(s), t = KMP_init(s);
if(n%(n-t-1) == 0)
printf("%d\n", n/(n-t-1));
else
puts("1");
}
return 0;
}
可以問你 n%(n-t-1) 的想法嗎
KMP回傳回來應該是最後一個這個字不符合時從哪個字開始找起對吧?