CF1056E Check Transcription 题解

· · 题解

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

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

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

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

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

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

暴力匹配的算法流程如下(设当前在 s 中匹配到的位置为 p,r_0 的哈希值为 h_0,r_1 的哈希值为 h_1):

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

{\large\color{#00CD00}\text{代码}}
#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;
}