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;
    }
  • 相关阅读:
    反向传播错漏百出小推导
    使用git遇到的
    Cost Function in Logistic Regression and Neural Network
    鼠标左键长按功能的实现
    同类控件的统一操作(以TCHECKBOX为例)
    HLP帮助文件源文件RTF文件的编写
    FORMAT 的用法
    DELPHI6中DSGNINTF.DCU找不到时的解决方法
    使窗体处于可“移动”,可改变“大小”状态中
    系统菜单的控制,使菜单项灰显及恢复功能
  • 原文地址:https://www.cnblogs.com/vocaloid01/p/9514170.html
Copyright © 2011-2022 走看看