POJ2406 Power Strings(KMP)

2018-07-03 01:01:09来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 56162   Accepted: 23370

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
 
 
kmp的经典应用
设$len$表示字符串的长度,$next[i]$表示$i$号字符串的最长公共前后缀的长度
如果$len mod next[len] == 0$,那么循环节的长度为$n / next[len]$
 
#include<cstdio>
#include<cstring>
using namespace std;
const int MAXN = 1e6 + 10;
char s[MAXN];
int fail[MAXN];
int main() {
#ifdef WIN32
    freopen("a.in", "r", stdin);
    //freopen("a.out", "w", stdout);
#endif
    while(scanf("%s", s + 1) && s[1] != '.') {
        int N = strlen(s + 1), now = 0;
        for(int i = 2; i <= N; i++) {
            while(now && s[i] != s[now + 1]) now = fail[now];
            if(s[i] == s[now + 1]) now++;
            fail[i] = now;
        }
        if(N % (N - fail[N]) == 0) printf("%d\n", N / (N - fail[N]));
        else printf("1\n");
    }
    return 0;
}

 

 
 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:【算法】关于图论中的最小生成树(Minimum Spanning Tree)详解

下一篇:31.QPainter-rotate()函数分析-文字旋转不倾斜,图片旋转实现等待