zoukankan      html  css  js  c++  java
  • POJ2406 Power Strings(KMP)

    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

     
     
    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 - fail[N]));
            else printf("1
    ");
        }
        return 0;
    }
     
     
  • 相关阅读:
    VueCLI3如何更改安装时的包管理器
    查天气43课-46课
    【Python第31课到42课】
    【Python第16课到30课 】
    Python笔记
    【AC】九度OJ题目1153:括号匹配问题
    【AC】九度OJ题目1436:Repair the Wall
    【WA】九度OJ题目1435:迷瘴
    Matlab图片改颜色通道不改名存储
    [Linux 操作] awk操作の 打印图片路径
  • 原文地址:https://www.cnblogs.com/zwfymqz/p/9255867.html
Copyright © 2011-2022 走看看