天天看点

hdu3746(next数组解决)

题目大意:给一个字符串,问你向尾部或首部最少加几个可以使这个字符串由n个相同的小字符串组成,且n > 1。

题目的要点:1、首尾皆可以加字符;

                    2、 要求最短重复子串;

                    3、 重复次数必须大于1;

然后就是怎么解决了。我的解决方法是next数组,举个例子吧:

字符串: a    b    c    a    b    c    a    b    c    a    \0

next[ ] : -1    0    0    0    1    2    3    4    5    6    7

结果是:  cir = len - next[len]     cir就是最短重复子串的长度

             if(len%cir == 0)     那么就不用加(前提是cir != 0,也就是只重复一次的时候)

             x = cir - (len%cir)    就是要添加的字符个数

       其实当next数组成递增趋势上升时(要持续上升不是断断续续那种),就是第二个最短重复子串从第二个字符开始的next数组,进而我们也可以看做next数组从后面开始算重复数组,也就是它是向字符串串首加字符,然而我们也可以看出其实从首或是从尾加,答案并不变的。

下面是代码实现:

#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>

using namespace std;

char str[];
int nt[];
void get_next()
{
    int len = strlen(str);
    int i = , j = -;

    nt[] = -;
    while(i < len)
    {
        if(j == - || str[i] == str[j])
            nt[++i] = ++j;
        else
            j = nt[j];
    }
    return ;
}

int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        scanf("%s", str);

        get_next();

        int len = strlen(str);
        int cir = len - nt[len];

        if(len%cir ==  && cir != len)
            printf("0\n");
        else
            printf("%d\n", cir-(len%cir));
    }
    return ;
}
           

若有错,请大家多多指教~~~