[kuangbin带你飞]专题十六 KMP & 扩展KMP & Manacher E - Period HDU - 1358(循环节kmp)

时间:2019-08-15
本文章向大家介绍[kuangbin带你飞]专题十六 KMP & 扩展KMP & Manacher E - Period HDU - 1358(循环节kmp),主要包括[kuangbin带你飞]专题十六 KMP & 扩展KMP & Manacher E - Period HDU - 1358(循环节kmp)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

E - Period HDU - 1358

题目链接:https://vjudge.net/contest/70325#problem/E

题目:

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.

InputThe 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.
OutputFor 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个字母之前的字符串如果具有循环特性给出字符串的长度和其循环节的数量
思路:i-next[i]是如果具有循环节的话,那么他就是循环节的长度,当i%(i-next[i])==0的话,那么i这么长的字符串就是具有循环特性,那么i/(i-next[i])就是循环节的数量了
注意下列代码注释的部分不能那样写,因为他是优化过的kmp匹配,不能匹配到每个next[i],而一般的kmp就会每个都匹配到,从而不会造成漏解

// 
// Created by HJYL on 2019/8/15.
//
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <queue>
#include <stack>
#include <set>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
using namespace std;
const int maxn=1e6+10;
char str[maxn];
int nextt[maxn];
void getnext()
{
    int i=0,j=-1;
    nextt[0]=-1;
    int n=strlen(str);
    while(i<n)
    {
        if(j==-1||str[i]==str[j])
        {
            i++,j++;
            //if(str[i]!=str[j])
                nextt[i]=j;
           // else
               // nextt[i]=nextt[j];
        } else
            j=nextt[j];
    }
}
int main()
{
    //freopen("C:\\Users\\asus567767\\CLionProjects\\untitled\\text","r",stdin);
    int T;
    int kase=1;
    while(~scanf("%d",&T)){
        if(T==0)
            break;
        scanf("%s",str);

        getnext();
        printf("Test case #%d\n",kase++);
        int len=strlen(str);
        for(int i=1;i<=len;i++)
        {
            if(nextt[i]!=0&&i%(i-nextt[i])==0)
               printf("%d %d\n",i,i/(i-nextt[i]));
        }
        printf("\n");
    }
    return 0;
}

原文地址:https://www.cnblogs.com/Vampire6/p/11360537.html