• 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;
        }
    }
    
  • 相关阅读:
    《UNIX环境高级编程》笔记--UNIX标准化及实现
    SPOJ1811最长公共子串问题(后缀自动机)
    一个leetcode解题报告类目,代码很简洁
    字符压缩题目
    求最佳会议地点
    实现树的横向指针
    lower_bound与upper_bound
    求到所有房子距离和最小的新房子
    增加限制条件的矩阵求和
    切分数组来得到一定的和
  • 原文地址:https://www.cnblogs.com/caowenbo/p/11852215.html
Copyright © 2020-2023  润新知