• poj 1961 Period (kmp next 数组的应用)


    http://poj.org/problem?id=1961

    Period
    Time Limit: 3000MS   Memory Limit: 30000K
    Total Submissions: 10855   Accepted: 4995

    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 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中next数组的理解与应用
    代码:
     1 #include<iostream>
     2 #include<string.h>
     3 #include<stdio.h>
     4 using namespace std;
     5 #define MAX 1000000
     6 void get_next(char *str,int *next)
     7 {
     8     int i=0,j=-1;
     9     int tlen=strlen(str);
    10     next[0]=-1;
    11     while(i<tlen)
    12     {
    13         if(j==-1||str[i]==str[j])
    14         {
    15             i++;
    16             j++;
    17             if(i%(i-j)==0&&i/(i-j)>1)  //主要代码
    18                 printf("%d %d\n",i,i/(i-j));
    19             if(str[i]!=str[j])
    20                 next[i]=j;
    21             else
    22                 next[i]=next[j];
    23         }
    24         else
    25             j=next[j];
    26     }
    27 }
    28 char str[MAX+10];
    29 int next[MAX+10];
    30 int main()
    31 {
    32     int t=1,n;
    33     while(~scanf("%d",&n)&&n)
    34     {
    35         scanf("%s",str);
    36         printf("Test case #%d\n",t++);
    37         get_next(str,next);
    38         printf("\n");
    39     }
    40     return 0;
    41 }
  • 相关阅读:
    iOS coreData
    具体解释首页被K后SEOer必做的三大排除方法!
    linux VIM基本命令
    0046算法笔记——【随机化算法】舍伍德随机化思想解决跳跃表问题
    android新浪分享实例
    DIV固定在页面某个位置,不随鼠标滚动而滚动
    迷宫问题算法分析
    ExtJs选择器
    第二篇Activity:2、任务和返回堆栈(Tasks and Back Stack)之基本介绍
    面试题,将数字依次按三角形输出,每行一个数字
  • 原文地址:https://www.cnblogs.com/crazyapple/p/3109348.html
Copyright © 2020-2023  润新知