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;
        }
    }
    
  • 相关阅读:
    Boa移植到Android——ztg
    How to port lighttpd to Android
    android 4.4源码下载——百度云盘地址
    CentOS7——解压7z文件——p7zip
    android—mm—mmm—没有规则可以创建target/product/generic/obj/SHARED_LIBRARIES
    日常美食 小纪
    日常美食 小纪
    上海植物园
    上海之行(一)田子坊
    上海之行(一)田子坊
  • 原文地址:https://www.cnblogs.com/caowenbo/p/11852215.html
Copyright © 2011-2022 走看看