HDU-3746 Cyclic Nacklace

KMP算法与Next数组应用
本文通过一个具体实例介绍了KMP算法中Next数组的应用,展示了如何通过Next数组找到字符串的最长公共前后缀,并解决了一个特定的问题。文章包括完整的代码实现。

题目链接:https://vjudge.net/problem/HDU-3746

这道题利用了KMP里next数组的性质

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int N=100000+10; 
char b[N];
int next0[N];  
void find_next()
{
	int len=strlen(b);
	int k=-1;
	next0[0]=-1;
	int j=0;
	while(j<len) //多求一位
	{
		if(k==-1||b[j]==b[k])
		{
			j++;
			k++;
			next0[j]=k;
		}
		else
		{
			k=next0[k];
		}
	}
}
int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%s",b);
		find_next();
		int len=strlen(b);
		if(next0[len]==0) //最长公共前缀长度 
		{
			printf("%d\n",len);
			continue;
		}
		int t=len-next0[len];
		if(len%t==0) printf("0\n");
		else printf("%d\n",t-len%t);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值