zoukankan      html  css  js  c++  java
  • HDU1358——Period(KMP求最小循环节)

    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
    

    题意:
    给出一字符串,找出由两个或以上相同的子字符串组成的前缀,输出前缀长度及其中相同的子字符串数。

    思路:
    Kmp求最小循环节。
    一个长为N的字符串(0-N-1)的最小循环节长度 = 字符串长度 - Next[N]。

    代码:

    #include <iostream>
    #include <cstdio>
    
    using namespace std;
    
    int Next[1000005];
    int N;
    
    void getNext(char s[])
    {
        int i = -1;
        int j = 0;
        Next[0] = -1;
        while(j<N)
        {
            if(i == -1 || s[j] == s[i])
            {
                Next[++j] = ++i;
            }
            else i = Next[i];
        }
    }
    
    int main()
    {
        char s[1000005];
        int flag = 0;
        while(scanf("%d",&N) && N)
        {
            scanf("%s",s);
            getNext(s);
            printf("Test case #%d
    ",++flag);
            for(int i=2 ; i<=N ; i++)
            {
                int sum = i-Next[i];
                if(i%sum == 0 && i>sum)//排除i==sum的情况。 
                {
                    printf("%d %d
    ",i,i/sum);
                }
            }
            printf("
    ");
        }
    
        return 0;
    }
  • 相关阅读:
    Linux虚拟机的安装(使用Centos6.3)
    【转载】接口测试用例的设计原则
    Oracle PLSQL游标、游标变量的使用
    利用shell脚本将Oracle服务器中数据定时增量刷新到ftp服务器中
    源码安装rlwrap 0.43(为了方便使用linux下的sqlplus)
    Oracle自定义脱敏函数
    Oracle分析函数FIRST_VALUE、LAST_VALUE
    MYSQL性能测试工具SYSBENCH
    OEL7.6源码安装MYSQL5.7
    OEL7.6安装Oracle Database 19C(VERSION 19.3.0.0)
  • 原文地址:https://www.cnblogs.com/vocaloid01/p/9514170.html
Copyright © 2011-2022 走看看