武辰延的字符串(思维+二分字符串前缀)

62 篇文章 2 订阅
11 篇文章 0 订阅

众所周知,武辰延很喜欢字符串。

这天,他对着两个字符串 s 和 t 发呆,他发现这两个串的前缀有很多相似的地方,s 的两个前缀连接起来竟也是 t 的前缀。

武辰延想知道有多少对 s 的非空前缀连接起来是 t 的前缀。

形式化地讲,我们把si​ 看作字符串 s 长度为 i 的前缀。

对于一对前缀 (si​,sj​) (允许 i=j)而言,当满足si+sj​=ti+j​ 时,我们认为这两个 s 的前缀拼接后等于 t 的一个前缀。

两对 s 的前缀 (si​,sj​) 与 (si′​,sj′​) 不同当且仅当 i'j′ 。 


思路:

因为在找到某个前缀匹配时,前缀的前缀也一定匹配,因此具有单调性,可以二分找。(算个trick吧)

剩下就是哈希了


#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e5+100;
typedef long long LL;
const LL base=131;
const LL mod=998244353;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
char s1[maxn],s2[maxn];
LL sum1[maxn],sum2[maxn],p[maxn];
LL cal(LL l,LL r,LL sum[]){
    return (sum[r]%mod-sum[l-1]*p[r-l+1]%mod+mod)%mod;
}
bool check(LL l1,LL r1,LL l2,LL r2,LL len2){
    LL t1=cal(l1,r1,sum1);
    LL t2=0;
    if(r2>len2) t2=0;
    else t2=cal(l2,r2,sum2);
    if(t1==t2) return true;
    else return false;
}
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  p[0]=1;
  for(LL i=1;i<maxn;i++) p[i]=p[i-1]*base%mod;
  cin>>(s1+1);LL len1=strlen(s1+1);
  cin>>(s2+1);LL len2=strlen(s2+1);
  for(LL i=1;i<=len1;i++) sum1[i]=(sum1[i-1]*base%mod+(s1[i]-'a'+1)%mod)%mod;///不能减-'a',会变0然后冲撞,以后字符串hash统一写s[i]就好
  for(LL i=1;i<=len2;i++) sum2[i]=(sum2[i-1]*base%mod+(s2[i]-'a'+1)%mod)%mod;
  LL ans=0;
  for(LL i=1;i<=len2;i++){
     if(s1[i]!=s2[i]) break;
     if(s2[i+1]!=s1[1]) continue;///L卡到1的边界
     LL l=1;LL r=len1;///二分第一个串的额外前缀长度为mid
     while(l<r){
        LL mid=(l+r+1)>>1;
        if(check(1,mid,i+1,i+mid,len2)) l=mid;
        else r=mid-1;
     }
     ans+=(l);
  }
  cout<<ans<<"\n";
return 0;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值