zoukankan      html  css  js  c++  java
  • 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]));
        }
    }
  • 相关阅读:
    php安装xcache (5.4)
    nginx博客系统(内含nginx图片缩略图处理代码,不错)
    一个mysql开启多个端口
    mysql源码重启
    ecshop支付时减库存方法
    n阶幻方问题
    codeforces 710A King Moves(水)
    关于ios::sync_with_stdio(false);和 cin.tie(0)加速c++输入输出流
    codeforces 701C. They Are Everywhere(尺取法)
    codeforces 701 B. Cells Not Under Attack
  • 原文地址:https://www.cnblogs.com/Patt/p/4921848.html
Copyright © 2011-2022 走看看