• 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;
        }
    }
    
  • 相关阅读:
    AJAX初识
    PE文件---导入表,导出表
    PE文件学习(基础)
    Android so(ELF)文件解析
    安卓加固方案从落地加载到类指令抽取编写报告
    安卓逆向从0到1学习总结
    DEX文件解析--7、类及其类数据解析(完结篇)
    网络设备配置--10、利用ACL配置访问控制
    网络设备配置--9、利用ppp协议实现点对点认证
    网络设备配置--8、利用ospf配置动态路由
  • 原文地址:https://www.cnblogs.com/caowenbo/p/11852215.html
Copyright © 2020-2023  润新知