HDU 3746 Cyclic Nacklace KMP

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

int len;

void getNext(char *s, int *nex)
{
    nex[0] = -1;
    int i = 0, j = -1;
    while(i < len)
    {
        if(j == -1 || s[i] == s[j])
        {
            i++, j++;
            nex[i] = j;
        }
        else j = nex[j];
    }
}

int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        char s[100100];
        scanf("%s", s);
        len = strlen(s);
        int nex[100100];
        getNext(s, nex);
        int a = nex[len];
        if(2*a < len) printf("%d\n", len-2*a);  //第一种情况,后面直接补
        else if(len%(len-a) == 0) printf("0\n");  //正好
        else printf("%d\n", len-a-(len%(len-a)));  //循环节为len-a,前面开头那段
    }
    //system("pause");
    return 0;
}
上一篇:斜率优化dp


下一篇:数据结构实验一:单链表就地翻转