[POJ 2406] Power Strings【KMP】

  • 2018-02-20
  • 0
  • 0

Problem:

Time Limit: 3000MS Memory Limit: 65536K

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

Hint

This problem has huge input, use scanf instead of cin to avoid time limit exceed.

Source

Waterloo local 2002.07.01

Solution:

本题是 KMP 的变形,考查了自匹配 nxt[] 数组的性质。

设原串 s 长度为 len,令 k =  len - nxt[len],则若 k | len,我们可以得到:

  • len = c * k (c ∈ N*)s1..(c-1)k == sk+1..ck
  • s1..k == sk+1..2k == …… == s(c-1)k+1..ck

最大循环节数 c = len / k。否则若 k 不能整除 len,则 c = 1

Code: O(T|s|) [5564K, 141MS]

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;

char s[1000005];
int nxt[1000005];

int main(){
	while(scanf("%s", s + 1) != EOF && s[1] != '.'){
		int len = strlen(s + 1);
		nxt[1] = 0;
		for(register int i = 2, j = 0; i <= len; i++){
			while(j && s[j + 1] != s[i]) j = nxt[j];
			if(s[j + 1] == s[i]) j++;
			nxt[i] = j;
		}
		if(len % (len - nxt[len])) puts("1");
		else printf("%d\n", len / (len - nxt[len]));
	}
	return 0;
}

评论

还没有任何评论,你来说两句吧



常年不在线的QQ:
49750

不定期更新的GitHub:
https://github.com/Darkleafin


OPEN AT 2017.12.10

如遇到代码不能正常显示的情况,请刷新页面。
If the code cannot be displayed normally, please refresh the page.


发现一个优美的网站:
https://visualgo.net/en
















- Theme by Qzhai