zoukankan      html  css  js  c++  java
  • HDU 1358 Period(KMP next数组运用)

    Period

    Problem Description
    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 AK , 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
     
    题目大意:给定一串字符串求当第i个位置时str[1,i]构成循环,输出这个位置i和循环节的个数
    思路: 果然kmp next数组的功能是如此强大啊,前面刚学一种循环节的判定,现在又是寻找循环节的个数,此处字符串的下标是从1开始的,next数组的下标也从1开始,对于每一个位置i,我们i定义一个变量k = i-next[i];如果i%k==0;也就代表着i位置之前的字符串一定是一个由x个循环节表示出来的,循环节的长度为k,个数x即为i/k;
     
    #include<iostream>
    #include<algorithm>
    #include<string>
    
    using namespace std;
    const int maxn = 1000005;
    int nex[maxn], n, T = 0;
    void Getnext(string str, int len)
    {
        nex[0] = -1; int k = -1;
        for (int i = 1; i < len; i++) {
            while (k > -1 && str[k + 1] != str[i])k = nex[k];
            if (str[k + 1] == str[i])k++;
            nex[i+1] = k+1;
        }
    }
    int main()
    {
        ios::sync_with_stdio(false);
        while(cin>>n&& n){
            T++; 
            string str;
            cin >> str;
            Getnext(str, n);
            cout << "Test case #" << T << endl;
            for (int i = 1; i <= n; i++) {
                int k = i - nex[i];
                if (nex[i] == 0)continue;
                if (i%k == 0)
                    cout << i << " " << i / k << endl;
            }cout << endl;//不要忘了在输出一个换行!
        }
        return 0;
    }
  • 相关阅读:
    swift高速入门,三分钟上手
    针对Azure微软与世纪互联的合作方式
    Major compaction时的scan操作
    利用ENVI FX从RGB提取建筑物轮廓
    自己动手写处理器之第二阶段(1)——可编程逻辑器件与PLD电路设计流程
    CSS Sprites(基本写法,怎样使用)
    00104_网络通信协议
    雷林鹏分享:XML 语法规则
    雷林鹏分享:XML 验证
    雷林鹏分享:XML 属性
  • 原文地址:https://www.cnblogs.com/wangrunhu/p/9531031.html
Copyright © 2011-2022 走看看