zoukankan      html  css  js  c++  java
  • Period(循环节 nxt数组的应用)

    For each prefix of a given string S with N characters (each character has an ASCII code between 97 and 126, inclusive), we want to know whether the prefix is a periodic string. That is, for each i (2 <= i <= N) we want to know the largest K > 1 (if there is one) such that the prefix of S with length i can be written as A K , that is A concatenated K times, for some string A. Of course, we also want to know the period K. 

    Input

    The input file consists of several test cases. Each test case consists of two lines. The first one contains N (2 <= N <= 1 000 000) – the size of the string S. The second line contains the string S. The input file ends with a line, having the number zero on it. 

    Output

    For each test case, output “Test case #” and the consecutive test case number on a single line; then, for each prefix with length i that has a period K > 1, output the prefix size i and the period K separated by a single space; the prefix sizes must be in increasing order. Print a blank line after each test case. 

    Sample Input

    3
    aaa
    12
    aabaabaabaab
    0

    Sample Output

    Test case #1
    2 2
    3 3
    
    Test case #2
    2 2
    6 2
    9 3
    12 4

    给出一个字符串,让你求出1~i都有循环节

    以及循环节多长

    在理解了nxt数组之后 我们很容易能够发现循环节的规律我们通过nxt可以推得

    #define LOCAL
    #include<bits/stdc++.h>
    using namespace std;
    char s[1000005];
    int nxt[1000005];
    int n;
    void get_nxt()
    {
        int i=0;
        int k=-1;
        nxt[0]=-1;
        while(i<n)
        {
            if(k==-1||s[k]==s[i])
            {
                k++;
                i++;
                nxt[i]=k;
            }
            else
            {
                k=nxt[k];
            }
        }
        return ;
    }
    int main()
    {
        #ifdef LOCAL
        freopen("in.txt","r",stdin);
        freopen("out.txt","w",stdout);
        #endif // LOCAL
        int cas=0;
        while(~scanf("%d",&n))
        {
            if(n==0) break;
            cas++;
            cout<<"Test case #"<<cas<<endl;
            scanf("%s",s);
            get_nxt();
            for(int i=2;i<=n;i++)
            {
                if(i%(i-nxt[i])==0)
                {
                    if(nxt[i]!=0)
                    //cout<<i<<" "<<i-nxt[i]<<" ";
                    printf("%d %d
    ",i,i/(i-nxt[i]));
                }
            }
            cout<<endl;
        }
    }
    
  • 相关阅读:
    [转]ubuntu的which、whereis、locate和find命令
    [转]理解SSL(https)中的对称加密与非对称加密
    SSL交互过程
    [转]程序开发基础学习二(C++ Google Style 命名规则)
    函数内动态分配内存
    sizeof和strlen
    Sublime Text 3 安装Package Control
    [转]使用Openssl的AES加密算法
    正则表达式
    论文书写常见问题与技巧
  • 原文地址:https://www.cnblogs.com/caowenbo/p/11852215.html
Copyright © 2011-2022 走看看