hdu 3746 Cyclic Nacklace(求最少添加几个字符使得字符串是由n(n>=2)个循环节组成的)

代码:

#include<cstdio>
#include<cstring>
using namespace std;

char a[100005];
int next[100005];
int LCPS[100005];
int n,m;

void GetLCPS()
{
    int j=0;
    int k=-1;
    int len=strlen(a);
    next[0]=-1;
    while(j<len)
    {
        if(k==-1||a[k]==a[j])
        {
            LCPS[j++]=++k;
            next[j]=k;
        }
        else
        {
            if(k-1>=0)
                k=LCPS[k-1];
            else
                k=-1;
        }
    }
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        //scanf("%s",b);
        scanf("%s",a);
        GetLCPS();
        int len=strlen(a);
        int cir=len-next[len];
        if(cir==1)
        {
            printf("0\n");
            continue;
        }
        int r=len%cir;
        if(len==cir)
        {
            printf("%d\n",cir);
            continue;
        }
         if(r==0)
         {
             printf("0\n");
             continue;
         }
        printf("%d\n",cir-r);
    }
    return 0;
}


你可能感兴趣的:(KMP)