HDU——3746 【kmp】|| next数组的活用 || 【经典题】

CC always becomes very depressed at the end of this month, he has checked his credit card yesterday, without any surprise, there are only 99.9 yuan left. he is too distressed and thinking about how to tide over the last days. Being inspired by the entrepreneurial spirit of "HDU CakeMan", he wants to sell some little things to make money. Of course, this is not an easy task. 

As Christmas is around the corner, Boys are busy in choosing christmas presents to send to their girlfriends. It is believed that chain bracelet is a good choice. However, Things are not always so simple, as is known to everyone, girl's fond of the colorful decoration to make bracelet appears vivid and lively, meanwhile they want to display their mature side as college students. after CC understands the girls demands, he intends to sell the chain bracelet called CharmBracelet. The CharmBracelet is made up with colorful pearls to show girls' lively, and the most important thing is that it must be connected by a cyclic chain which means the color of pearls are cyclic connected from the left to right. And the cyclic count must be more than one. If you connect the leftmost pearl and the rightmost pearl of such chain, you can make a CharmBracelet. Just like the pictrue below, this CharmBracelet's cycle is 9 and its cyclic count is 2: 

题意大致就是给你一个串,先问你应在开头或者末尾处添加几个字符使得合成后的串的周期为2;

思路:主要是使用了next数组的一个性质就是next[len]储存的是这个字符串的最大的前缀后缀值,那么len-next[len]就表示了这个串的循环体也就是最小的循环结构,

于是,就判断这个循环节是不是可以整除len(len/length的结果不可以为1,这属于另一种情况),如果可以的话,那么就不在需要添加字符输出0。

否则,就计算一下还需要添加多少字符,用整个循环体的长度减去当前最后那几位构不成循环体的那部分长度:length-nxt[len]%length;

代码:

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

using namespace std;

const int maxn=4e5+10;

int nxt[maxn];
char nm[maxn];
int put[maxn];
int len;

void getnxt()
{
    int i=0,j=-1;
    nxt[0]=-1;
    while(i<len)
    {
        if(j==-1||nm[i]==nm[j])
            nxt[++i]=++j;
        else j=nxt[j];
    }
}

int main()
{
   int t;
   scanf("%d",&t);
   while(t--)
   {
       scanf("%s",nm);
       len=strlen(nm);
       getnxt();
       int length = len - nxt[len];//先求出循环节的长度
       if(len != length && len % length == 0)第一种情况,如果循环节的长度可以被len整除,且结果不是1,那就输出0,因为如果结果是1,那么就需要len个字符来凑成2个周期
            printf("0\n");
       else
       {
           int add=length-nxt[len]%length;
           printf("%d\n",add);
       }
   }
    return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值