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;
    }
  • 相关阅读:
    标准粒子群算法(PSO)
    Java开发中的23种设计模式详解
    分布式事务
    sjk 分页
    有用吗2
    有用吗1
    存储过程
    在虚拟机Linux安装Redis
    ajax调用WebAPI添加数据
    SVN安装和使用(简单版)
  • 原文地址:https://www.cnblogs.com/vocaloid01/p/9514170.html
Copyright © 2011-2022 走看看