BNUOJ 34990 Justice String (基于hash的LCP)

本文介绍了一种解决特定字符串匹配问题的算法实现,该问题要求在给定字符串A中找到一个子串s,通过最多修改两个字符使s与另一字符串B相等。文章详细解释了如何通过枚举起点的方法计算两字符串的最长公共前缀(LCP),并最终确定满足条件的子串s的起始位置。

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

题目:http://www.bnuoj.com/v3/problem_show.php?pid=34990

题意:给定字符串A和B,在A里面找一个子串s,在s里面最多修改2个字符后使得s和B相同。求s的起始位置。


分析:枚举起点求s和B的LCP。看s最多修改两次后是否满足条件。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef unsigned long long ULL;
const int maxn = 2e5+6;
const int seed = 131;
ULL H[maxn],X[maxn];
char s1[maxn],s2[maxn];
int Len1,Len2,L;
void Init()
{
	H[L]=0;
	for(int i=L-1;i>=0;i--)
		H[i]=H[i+1]*seed+s1[i]-'a';
	X[0]=1;
	for(int i=1;i<L;i++)
		X[i]=X[i-1]*seed;
}
inline ULL GetHash(int i,int L) //
{
	return H[i]-H[i+L]*X[L];
}
int LCP(int a,int b)
{
	int ret=0,down=1,up=L-b,mid;
	while(down<=up)
	{
		mid=(down+up)>>1;
		if(GetHash(a,mid)==GetHash(b,mid))
		{
			down=mid+1;
			if(mid>ret)	
				ret=mid;
		}
		else
			up=mid-1;
	}
	return ret;
}
int main()
{
	int ncase,i,j,f1,f2,f3,ans;
	scanf("%d",&ncase);
	for(int T=1;T<=ncase;T++)
	{
		scanf("%s%s",s1,s2);
		Len1=strlen(s1);
		Len2=strlen(s2);
		L=Len1+Len2;
		strcat(s1,s2);
		Init();
		for(i=0;i<=Len1-Len2;i++)
		{
			f1=LCP(i,Len1);
			if(f1==Len2)
				break;
			f1++;
			f2=LCP(i+f1,Len1+f1);
			if(f1+f2==Len2)
				break;
			f2++;
			f3=LCP(i+f1+f2,Len1+f1+f2);
			if(f1+f2+f3==Len2)
				break;
		}
		printf("Case #%d: %d\n",T,((i<=Len1-Len2)?i:-1));
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值