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;
    }
  • 相关阅读:
    day18:正则表达式和re模块
    finance1:专业词汇
    Iterator & Iterable 和 Comparable&Comparator
    pandas中三种索引方式(.loc.iloc.ix)
    XML序列化与反序列化
    控件蓝图里控件绑定问题
    Mouse Properties(鼠标属性)
    cSV
    从父控件移除控件
    是否显示鼠标指针
  • 原文地址:https://www.cnblogs.com/vocaloid01/p/9514170.html
Copyright © 2011-2022 走看看