POJ 1961 KMP(当前重复次数)

题意:
      前缀重复次数,举个例子,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 + 100

int 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
" ,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
" ,i ,tmp);
            }
         }
         printf("
");
     }
     return 0;
} 
         
          

原文地址:https://www.cnblogs.com/csnd/p/12063062.html