#kmp#洛谷 2375 jzoj 3756 loj 2246 codevs 3319 动物园

本文介绍了一种用于处理字符串前缀和后缀匹配问题的高效算法,并通过实例详细解析了算法的具体实现过程。该算法能够在匹配失败时更新答案数组,同时处理不重叠情况,最终输出所有可能的匹配组合数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

求字符串 S S S的前缀i中
KaTeX parse error: Can't use function '$' in math mode at position 6: \prod$̲前缀与后缀不重叠的数量$+1


分析

初级版本 洛谷 3435
所以说其实可以在匹配 f a i l fail fail的时候顺带 a n s [ i ] = a n s [ j ] + 1 ans[i]=ans[j]+1 ans[i]=ans[j]+1
然而不重叠的话就特判特判就好了


代码

#include <cstdio>
#include <cstring>
int n,fail[1000001],len,j,answer,ans[1000001]; char s[1000001];
int in(){
	int ans=0; char c=getchar();
	while (c<48||c>57) c=getchar();
	while (c>47&&c<58) ans=ans*10+c-48,c=getchar();
	return ans;
}
void print(int ans){
	if (ans>9) print(ans/10);
	putchar(ans%10+48);
}
int main(){
	n=in();
	while (n--){
		scanf("%s",s+1); len=strlen(s+1); fail[1]=ans[0]=j=0; ans[1]=1;
        for (int i=2;i<=len;i++){//匹配fail
            while (j&&s[i]!=s[j+1]) j=fail[j];
            fail[i]=(j+=(s[i]==s[j+1])); ans[i]=ans[j]+1;
        }
        j=0; answer=1;
        for (int i=2;i<=len;i++){
        	while (j&&s[i]!=s[j+1]) j=fail[j];
        	j+=(s[i]==s[j+1]); while ((j<<1)>i) j=fail[j];//不重叠的必要是j*2>i
        	answer=(long long)answer*(ans[j]+1)%1000000007;
        }
        print(answer); putchar('\n');
	}
	return 0; 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值