您的位置:首页 > 其它

POJ 2406 Power Strings(KMP)

2016-08-05 22:11 211 查看
Power Strings

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
abcd
aaaa
ababab
.

Sample Output
1
4
3

题目大意:求字符串的周期。
解题思路:KMP算法的一部分,只需要求出next数组。对于next[len]与len,有以下几种情况

(1)2 * next[len] < len,这种情况说明中间的一段字符串既不与next[1...j]相等,也不与next[len - j + 1...len]相等,所以周期为1;

(2)2 * next[len] >= len

    ①len % (len - next[len]) == 0,这种情况说明原字符串有周期,周期长度为len - next[len],周期个数为len / (len - next[len]);

    ②len % (len - next[len] != 0,这种情况说明可能存在周期,但是最后一个周期没有完成,所以周期也是1。

代码如下:

#include <algorithm>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#define EPS 1e-6
#define INF INT_MAX / 10
#define LL long long
#define MOD 100000000
#define PI acos(-1.0)

const int maxn = 1000005;

int next[maxn];
char pattern[maxn];
int len;
void get_next()
{
memset(next,-1,sizeof(next));
next[1] = 0;
for(int i = 2,j = 0;i <= len;i++){
while(j > 0 && pattern[j + 1] != pattern[i])
j = next[j];
if(pattern[j + 1] == pattern[i])
j += 1;
next[i] = j;
}
}

int main()
{
while(scanf("%s",pattern + 1) != EOF && pattern[1] != '.'){
len = strlen(pattern + 1);
get_next();
int ans = 1;
if(2 * next[len] >= len && !(len % (len - next[len])))
ans = len / (len - next[len]);
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  POJ