標籤:kmp poj
題目連結:http://poj.org/problem?id=2406
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.
Source
Waterloo local 2002.07.01
題意:
求最小子串的迴圈次數;
思路:(轉)
KMP,next[]表示模式串如果第i位(設str[0]為第0位)與文本串第j位不匹配則要回到第next[i]位繼續與文本串第j位匹配。則模式串第1位到next[n]與模式串第n-next[n]位到n位是匹配的。所以思路和上面一樣,如果n%(n-next[n])==0,則存在重複連續子串,長度為n-next[n]。
例如:a b a b a b
next:-1 0 0 1 2 3 4
next[n]==4,代表著,首碼abab與尾碼abab相等的最長長度,這說明,ab這兩個字母為一個迴圈節,長度=n-next[n];
代碼如下:
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;#define MAXN 1000017int next[MAXN];int len;void getnext( char s[]){ int i = 0, j = -1; next[0] = -1; while(i < len) { if(j == -1 || s[i] == s[j]) { i++,j++; next[i] = j; } else j = next[j]; }}int main(){ char ss[MAXN]; int length; while(~scanf("%s",ss)) { if(ss[0] == '.') break; len = strlen(ss); getnext(ss); length = len - next[len];//注意 if(len%length == 0) printf("%d\n",len/length); else printf("1\n"); } return 0;}