Description
Solution
两个串S,T拼起来是回文串一定满足将T翻转后,有LCP(S,T’)=min(|S|,|T|),且剩余不同的部分是回文串
考虑朴素做法。我们枚举LCP长度,若剩下串为回文串则产生1的贡献
优化这个暴力。注意到我们仅需找到以每个位置为中心的最长回文子串,因此只需要预处理每一个串的所有回文字串,对于[l,r]的区间整体+1记为f。考虑二分每次询问的LCP长度,答案就是我们统计的f的区间和+LCP长度
字符串hash像玄学一样得分取决于模数(lll¬ω¬)
Code
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define rep(i,st,ed) for (register int i=st;i<=ed;++i)
#define drp(i,st,ed) for (register int i=st;i>=ed;--i)
#define fill(x,t) memset(x,t,sizeof(x))
typedef long long LL;
const int MOD=998244353;
const int N=800005;
LL p[N];
struct string {
char str[N]; int len;
LL h[N],s[N],f[N];
LL pre(int l,int r) {
return (h[r]-h[l-1]*p[r-l+1]%MOD+MOD)%MOD;
}
LL suf(int l,int r) {
return (s[l]-s[r+1]*p[r-l+1]%MOD+MOD)%MOD;
}
void pal(int x,int y) {
if (str[x]!=str[y]) return ;
int l=0,r=std:: min(len-y,x-1),ret=0;
for (;l<=r;) {
int mid=(l+r)>>1;
if (pre(x-mid,x)==suf(y,y+mid)) ret=mid,l=mid+1;
else r=mid-1;
}
f[x-ret]++; f[x+1]--;
}
void init(bool rev) {
scanf("%s",str+1); len=strlen(str+1);
rep(i,0,len) f[i]=0;
if (rev) rep(i,1,len/2) std:: swap(str[i],str[len-i+1]);
rep(i,1,len) h[i]=(h[i-1]*29LL%MOD+str[i]-'a')%MOD;
drp(i,len,1) s[i]=(s[i+1]*29LL%MOD+str[i]-'a')%MOD;
rep(i,1,len) {
pal(i,i);
pal(i,i+1);
}
rep(i,1,len) f[i]+=f[i-1];
rep(i,1,len) f[i]+=f[i-1];
}
} A,B;
int read() {
int x=0,v=1; char ch=getchar();
for (;ch<'0'||ch>'9';v=(ch=='-')?(-1):(v),ch=getchar());
for (;ch<='9'&&ch>='0';x=x*10+ch-'0',ch=getchar());
return x*v;
}
int lcp(int x,int y) {
int l=0,r=std:: min(A.len-x+1,B.len-y+1),ret=0;
for (;l<=r;) {
int mid=(l+r)>>1;
if (A.pre(x,x+mid-1)==B.pre(y,y+mid-1)) ret=mid,l=mid+1;
else r=mid-1;
}
return ret;
}
int main(void) {
p[0]=1; rep(i,1,N-1) p[i]=p[i-1]*29LL%MOD;
char ch=getchar();
A.init(0); B.init(1);
for (int T=read();T--;) {
int x=read(),y=read();
int len=lcp(x,y); LL ans=len;
ans+=A.f[std:: min(A.len,x+len)]-A.f[x];
ans+=B.f[std:: min(B.len,y+len)]-B.f[y];
printf("%lld\n", ans);
}
return 0;
}