POJ 1961 KMP(当前重复次数)

来源:互联网 发布:3d二次元制作软件 编辑:程序博客网 时间:2024/05/14 07:49
题意:
      前缀重复次数,举个例子,aaa 2的位置2个a,3的位置3个a
abcabcabc 6的位置两个abcabc,9的位置三个abcabc....

思路:
     KMP基础题目之一,直接利用的是next数组的特点,对于当前点i,

i - next[i] 表示的是最小重复子串长度,如果 i - next[i] 不等于0,同时i % (i - next[i]) == 0说明当前字符是循环子串的最后一位,那么tmp = i / (i - next[i]) 表示的是循环次数,如果tmp>1直接输出i  i / (i - next[i])就行了,就说这么多吧,只要理解了next数组就肯定会这个题目了。


#include<stdio.h>#include<string.h>#define N 1000000 + 100int next[N];char str[N];void get_next(int m){    int j ,k;    j = 0 ,k = -1;    next[0] = -1;    while(j < m)    {       if(k == -1 || str[j] == str[k])       next[++j] = ++k;       else k = next[k];    }    return ;}int main (){    int m ,i ,cas = 1;    while(~scanf("%d" ,&m) && m)    {         scanf("%s" ,str);         get_next(m);         printf("Test case #%d\n" ,cas ++);         for(i = 1 ;i <= m ;i ++)         {            if(i - next[i] && i % (i - next[i]) == 0)            {                 int tmp = i / (i - next[i]);                 if(tmp > 1)                 printf("%d %d\n" ,i ,tmp);            }         }         printf("\n");     }     return 0;}                    

0 0