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;
        }
    }
    
  • 相关阅读:
    Linux下常用的3种软件安装方式
    解决navicate 连接mysql数据库中文乱码的问题
    Lua 遍历Linux目录下的文件夹
    ubuntu 更改源
    ubuntu 下安装配置LAMP
    简述configure、pkg-config、pkg_config_path三者的关系
    linux 下库的深入调研
    Linux下的库操作工具-nm、ar、ldd、ldconfig和ld.so
    linux命令strings
    c++隐式类型转换和explicit
  • 原文地址:https://www.cnblogs.com/caowenbo/p/11852215.html
Copyright © 2011-2022 走看看