跳到正文

题解

CF1056E Check Transcription 题解

_Spectator_约 4 分钟
原文
文章信息与版本

文章信息

收录
2026年1月25日
更新
2026年1月25日
篇幅
约 4 分钟
题目
CF1056E

版本

  1. v2当前
  2. v1

可能更好的食用体验 ∣| 题目传送门


前置知识{\large\color{#00CD00}\text{前置知识}}

众所周知,字符串哈希可以实现快速且便捷的字符串匹配。若 hih_i 表示 s[1,i]s_{[1,i]} 的哈希值,则有:hi=hi−1×Base+sih_i=h_{i-1}\times Base+s_i(存储时常利用 unsigned long long 自然溢出或进行取模)。可以发现,这相当于把字符串当成一个 BaseBase 进制数,再将其转成十进制。由此不难得出,s[l,r]s_{[l,r]} 的哈希值为 hr−hl−1×Baser−l+1h_r-h_{l-1}\times Base^{r-l+1}。

而要判断两个字符串相同,只需要判断其在同一 BaseBase 值下的哈希值相同即可。


思路{\large\color{#00CD00}\text{思路}}

设 c0,c1c_0,c_1 分别为 tt 中 0/10/1 的数量。显然,满足条件的 r0,r1r_0,r_1 首先需要满足 ∣r0∣⋅c0+∣r1∣⋅c1=∣s∣|r_0|\cdot c_0+|r_1|\cdot c_1=|s|。那么我们可以枚举所有满足条件的正整数 ∣r0∣,∣r1∣|r_0|,|r_1|,然后利用字符串哈希暴力匹配即可。

暴力匹配的算法流程如下(设当前在 ss 中匹配到的位置为 pp,r0r_0 的哈希值为 h0h_0,r1r_1 的哈希值为 h1h_1):

  • 遍历 tt 中的每一个字符
  • 如果当前的字符为 00:求出 s[p,p+r0−1]s_{[p,p+r_0-1]} 的哈希值,记为 tmptmp,然后 p←p+r0p\gets p+r_0。
    • 如果 h0h_0 为空,则 h0←tmph_0\gets tmp。
    • 比较 tmptmp 与 h0h_0,如果 tmp≠h0tmp\ne h_0 则说明不合法,停止匹配。
  • 如果当前的字符为 11:与 00 的情况同理。
  • 成功匹配完成后,如果 h0≠h1h_0\ne h_1(题目要求 r0≠r1r_0\ne r_1),则增加答案。

此外,本题使用 unsigned long long 自然溢出存储哈希值会被 hack,因此需要对 109+710^9+7 取模。


代码{\large\color{#00CD00}\text{代码}}

C++
#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;
}
原文