24h購物| | PChome| 登入
2012-02-22 07:19:35| 人氣4,477| 回應1 | 上一篇 | 下一篇

[UVA] 10298 - Power Strings

推薦 0 收藏 0 轉貼0 訂閱站台

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;
}

台長: Morris
人氣(4,477) | 回應(1)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA] 11475 - Extend to Palindrome
此分類上一篇:[UVA] 455 - Periodic Strings

Dog
可以問你 n%(n-t-1) 的想法嗎

KMP回傳回來應該是最後一個這個字不符合時從哪個字開始找起對吧?
2012-03-18 20:57:40
版主回應
是, n-t-1 就是那段長
2012-03-19 13:52:36
是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文