Period HDU-1358

题目链接

题意:求字符串的前缀能否构成一个周期字符串,并输出周期次数。

思路:根据kmp算法next数组的性质为最长公共前后缀可知,设L为字符串的前缀长度,则有L(i)%(L(i)-next(i))==0则说明这个前缀为周期字符串,且次数为L(i)/(L(i)-next(i))。同时判断次数不为1。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int nextt[1000010];
char str[1000010];
void getnext(int len)
{                        
    int i=0,j=-1;
    nextt[i]=j;
    while(i<len)
    {
        if(j==-1||str[i]==str[j])
        {
            i++;j++;nextt[i]=j;
        }
        else
        j=nextt[j];
    }
}
int main()
{
    int n,i,j,ca=1;
    while(~scanf("%d",&n))
    {
        if(n==0)
        {
            break;
        }
        memset(str,0,sizeof(str));
        scanf("%s",str);
        getp(n);
        j=0;
        printf("Test case #%d\n",ca++);
        for(i=2;i<=n;i++)
        {
              if(i%(i-nextt[i])==0&&i/(i-nextt[i])!=1) 
              {
                 printf("%d %d\n",i,i/(i-nextt[i]));
              }
        }
        printf("\n");
    }
    return 0;
}

 

posted @ 2020-09-10 10:56  Ldler  Views(126)  Comments(0Edit  收藏  举报