• POJ 2406 Power Strings


    Time Limit: 3000MS   Memory Limit: 65536K
    Total Submissions: 38908   Accepted: 16170

    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

    -------------------------------------------------
    做之前已经知道tag是KMP了,但一时想不出如何KMP,乱写一发竟然AC了。
    把我乱搞的代码和正解都贴这里,留给自己回味吧。。。。。
     
    #include <cstdio>
    using namespace std;
    
    const int N(1e6+5);
    char s[N];
    int nt[N];
    
    int main(){
        for(int k, ls, p, ans; scanf("%s", s), *s!='.'; printf("%d
    ",ans)){
            k=0;
            for(int i=ls=1; s[i]; i++, ls++){
                for(;k&&s[k]!=s[i];k=nt[k-1]);
                nt[i]=s[k]==s[i]?++k:k;
            }
            p=ls-nt[ls-1];
            ans=1;
            if(p&&ls%p==0){
                ans=ls/p;
                for(int i=ls; i; i-=p)
                    if(i-nt[i-1]!=p){
                        ans=1;
                        break;
                    }
            }
        }
    }

    正解在此

    #include <cstdio>
    using namespace std;
    
    const int N(1e6+5);
    char s[N];
    int nt[N];
    
    int main(){
        for(int k, ls, p, ans; scanf("%s", s), *s!='.';){
            k=0;
            for(int i=ls=1; s[i]; i++, ls++){
                for(;k&&s[k]!=s[i];k=nt[k-1]);
                nt[i]=s[k]==s[i]?++k:k;
            }
            printf("%d
    ", ls%(ls-nt[ls-1])?1:ls/(ls-nt[ls-1]));
        }
    }
  • 相关阅读:
    【LeetCode每天一题】Pascal's Triangle(杨辉三角)
    【Redis】持久化
    【LeetCode每天一题】Swap Nodes in Pairs
    【LeetCode每天一题】Reverse String
    [bzoj2152]聪聪可可
    [bzoj3572][Hnoi2014]世界树
    Codeforces Round#409/VK-Cup 2017 Round2
    Educational Codeforces Round#19
    [bzoj4813][Cqoi2017]小Q的棋盘
    [bzoj4236]JOIOJI
  • 原文地址:https://www.cnblogs.com/Patt/p/4921848.html
Copyright © 2020-2023  润新知