codeforces 514C Watto and Mechanism

字符串哈希,枚举每一位即可

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#define DEBUG(x) cout<<#x<<" = "<<x<<endl
using namespace std;
typedef long long ll;
const int MAXN=6e5+10;
const ll MOD=1e15+37;
const ll p=1009;
set<ll> mem;
ll my_pow[MAXN];
ll get_hash(char s[],int len)
{
    ll r=0;
    for(int i=0;i<len;i++ ){
        r=(r*p+(s[i]-'a'+1)+MOD)%MOD;
    }
    return r;
}
void get_pow()
{
    my_pow[0]=1;
    ///最左边是最高位
    for(int i=1;i<MAXN ;i++ ){
        my_pow[i]=(my_pow[i-1]*p)%MOD;
    }
}
char s[MAXN];
int main()
{
    freopen("in.txt","r",stdin);
    int n,m;
    get_pow();
    scanf("%d%d",&n,&m);
    while(n--){
        scanf("%s",s);
        int len=strlen(s);
        ll t=get_hash(s,len);
        mem.insert(t);
    }
    while(m--){
        scanf("%s",s);
        int len=strlen(s);
        bool ok=false;
        ll h=get_hash(s,len);
        for(int i=0;i<len ;i++ ){
            for(int j=0;j<3 ;j++ ){
                char c='a'+j;
                if(s[i]==c)continue;
                ll t=(h+my_pow[len-i-1]*(c-s[i])+3*MOD)%MOD;
                if(mem.count(t)){
                    ok=true;break;
                }
            }
            if(ok)break;
        }
        ok?printf("YES
"):printf("NO
");
    }
}
原文地址:https://www.cnblogs.com/MalcolmMeng/p/9801965.html