POJ 2406 Power String

算出next数组.

对于任何一个循环字串,len-next[len]必为最小循环节长度

若len%(len-next[len])==0

即为循环字串,n=len/(len-next[len])

否则输出1

代码:

#include<cstdio>
#include<cstring>
using namespace std;
const int N=1e6+10;
char str[N]; 
int next[N],ans,len;
void make()
{
    int i=0,j=-1;
    next[i]=j;
    while(i<len)
    {
        if(j==-1||str[i]==str[j])
        {
            i++;
            j++;
            next[i]=j;
        }
        else
            j=next[j];
    }
}
int main()
{
    while(~scanf("%s",str))
    {
        if(str[0]=='.') break;
        len=strlen(str);
        make();
        int k=next[len];
        if(!(len%(len-k)))
            printf("%d\n",len/(len-k));
        else
            printf("1\n");
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/greengenius/p/9241362.html
今日推荐