前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >POJ2406 Power Strings(KMP)

POJ2406 Power Strings(KMP)

作者头像
attack
发布2018-07-05 10:55:57
2120
发布2018-07-05 10:55:57
举报

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

代码语言:javascript
复制
abcd
aaaa
ababab
.

Sample Output

代码语言:javascript
复制
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]$

代码语言:javascript
复制
#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;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-07-02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档