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;
    }
     
     
  • 相关阅读:
    C++函数四( 具有默认参数值的函数)
    C++函数三(内联函数和函数重载)
    C++函数二(函数的嵌套调用和递归调用)
    C++关于函数声明定义的位置
    C++函数一(标准库函数,自定义函数)
    C++扑克牌发牌游戏程序(包括C++随机数的解释)
    C++数组二(字符数组)
    C++数组一
    C++程序流程结构
    C++运算符与表达式
  • 原文地址:https://www.cnblogs.com/zwfymqz/p/9255867.html
Copyright © 2011-2022 走看看