首页 > 代码库 > hdu 3746 Cyclic Nacklace (KMP求最小循环节)

hdu 3746 Cyclic Nacklace (KMP求最小循环节)

//len-next[len]为最小循环节的长度
# include <stdio.h>
# include <algorithm>
# include <string.h>
using namespace std;
int len;
char a[100010];
int next[100010];
void Getnext()
{
    int i=0,j=-1;
    next[0]=-1;
    while(i<=len)
    {
        if(j==-1||a[i]==a[j])
            i++,j++,next[i]=j;
        else
            j=next[j];
    }
}
int main()
{
    int t;
    while(~scanf("%d",&t))
    {
        while(t--)
        {
            scanf("%s",a);
            len=strlen(a);
            Getnext();
            int ans=len-next[len];//最小循环节
            if(next[len]==0)
                printf("%d\n",len);
            else if(len%ans==0)
                printf("0\n");
            else
                printf("%d\n",ans-len%ans);
        }
    }
    return 0;
}

hdu 3746 Cyclic Nacklace (KMP求最小循环节)