POJ2406 KMP前缀周期

题意:
      给你一个字符串,长度小于1百万,问你他最多可以拆成集合相同字符串,例如abcabcabc 可以拆成3个abc,所以输出3.


思路:
      这个是比较常规的next应用,首先假设当前字符串长度n;那么
n - next[n]前缀为最短子串长度,如果n - next[n] != 0 && n / (n - next[n]) == 0,说明最后一个字符串是长度(n - next[n])子串的最后一位,那么直接输出n/(n-next[n])就行了,否则不是最后一位,输出1 ,例如abcab 最后n - next[n]应该等于3,说明最短子串是3,而5 % 3 == 2,说明最后一个是子串中的第二个,不能做到完全循环,所以要输出1


#include<stdio.h>
#include<string.h>

int next[1000005];
char str[1000005];

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];
    }
}

int main ()
{
    int n;
    while(~scanf("%s" ,str) && str[0] != '.')
    {
       n = strlen(str);
       get_next(n);
       //printf("%d
" ,n - next[n]);
       if(n % (n - next[n]) == 0)
       printf("%d
" ,n / (n - next[n]));
       else printf("1
");
    }
    return 0;
}
       



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