zoukankan      html  css  js  c++  java
  • POJ:2406-Power Strings(寻找字符串循环节)

    Power Strings

    Time Limit: 3000MS Memory Limit: 65536K

    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.


    就是一个寻找字符串的循环节,用KMP的思想,其实很简单就是len/(len-next[n])。(当然是在没有余数的情况下,不然就是1)


    #include<stdio.h>
    #include<cstring>
    #include<set>
    using namespace std;
    const int maxn = 1e6+100;
    char s[maxn];
    int next[maxn];
    
    void cal_next()
    {
        int k;
        next[0] = k = -1;
        int len = strlen(s);
        for(int i=1;i<len;i++)
        {
            while(k>-1 && s[i] != s[k+1])
                k = next[k];
            if(s[i] == s[k+1])
                k++;
            next[i] = k;
        }
    }
    
    int main()
    {
        while(scanf("%s",s))
        {
            if(s[0] == '.' && s[1] == 0)
                break;
            cal_next();
            int len = strlen(s);
            if(len%(len - next[len-1] - 1) == 0)
                printf("%d
    ",len/(len - next[len-1] - 1));
            else
                printf("1
    ");
            memset(s,0,sizeof(s));
        }
        return 0;
    }
    
  • 相关阅读:
    使用 nginx 作反向代理,启用 keepalive 时,遇到 502 错误的调查过程
    docker php安装模块报 Operation not permitted 解决方案
    记一次php压测性能影响很大的参数
    数据库第一章-学习笔记
    P1469 找筷子
    P1597 语句解析
    c语言优势 scanf("%d,%d",&a,&b)==2
    数据库第二章-学习笔记
    数据库 E-R 图之学习笔记
    数据库第六章-学习笔记
  • 原文地址:https://www.cnblogs.com/GoldenFingers/p/9107244.html
Copyright © 2011-2022 走看看