CF1056E Check Transcription 题解
_Spectator_ · · 题解
可能更好的食用体验
众所周知,字符串哈希可以实现快速且便捷的字符串匹配。若 unsigned long long 自然溢出或进行取模)。可以发现,这相当于把字符串当成一个
而要判断两个字符串相同,只需要判断其在同一
设
暴力匹配的算法流程如下(设当前在
- 遍历
t 中的每一个字符 - 如果当前的字符为
0 :求出s_{[p,p+r_0-1]} 的哈希值,记为tmp ,然后p\gets p+r_0 。- 如果
h_0 为空,则h_0\gets tmp 。 - 比较
tmp 与h_0 ,如果tmp\ne h_0 则说明不合法,停止匹配。
- 如果
- 如果当前的字符为
1 :与0 的情况同理。 - 成功匹配完成后,如果
h_0\ne h_1 (题目要求r_0\ne r_1 ),则增加答案。
此外,本题使用 unsigned long long 自然溢出存储哈希值会被 hack,因此需要对
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e6+5,Base=2233,Mod=1e9+7;
int n,m,c0,c1,ans;
int h[N],b[N]={1};
char t[N],s[N];
int get_hash(int l,int r){ //求 s[l...r] 的哈希值
return (h[r]-h[l-1]*b[r-l+1]%Mod+Mod)%Mod;
}
signed main()
{
cin>>t+1>>s+1;
n=strlen(t+1),m=strlen(s+1);
for(int i=1;i<=n;i++) t[i]=='0'?c0++:c1++;
for(int i=1;i<=m;i++)
{
b[i]=b[i-1]*Base%Mod;
h[i]=(h[i-1]*Base+s[i])%Mod;
//预处理:b[i]=Base^i, h[i]=s[1...i] 的哈希值
}
for(int x=1;x<m/c0;x++)
{
if((m-x*c0)%c1>0)continue;
int y=(m-x*c0)/c1;
//x=|r0|,y=|r1|
int h0=-1,h1=-1,p=1;
for(int i=1;i<=n;i++) //遍历 t
{
if(t[i]=='0'){
int tmp=get_hash(p,p+x-1); //求出哈希值
if(h0==-1)h0=tmp;
else if(tmp!=h0)goto err; //不合法
p+=x;
}
else{
int tmp=get_hash(p,p+y-1);
if(h1==-1)h1=tmp;
else if(tmp!=h1)goto err;
p+=y;
}
}
if(h0!=h1)ans++;
err:;
}
cout<<ans;
return 0;
}