Codeforces Round #291 (Div. 2) C. Watto and Mechanism hash函数

来源:互联网 发布:医药下单软件 编辑:程序博客网 时间:2024/06/13 11:17
C. Watto and Mechanism
time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs froms in exactly one position".

Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.

Input

The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·1050 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively.

Next follow n non-empty strings that are uploaded to the memory of the mechanism.

Next follow m non-empty strings that are the queries to the mechanism.

The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a''b''c'.

Output

For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).

Sample test(s)
input
2 3aaaaaacacacaaabaaccacacccaaac
output
YESNONO
题目要求,给一个字符串集,给定一个字符串,字符串集是否存在这个字符串相差一个字符的字符串,字符串很多,而且很长,想要存下来是不可能的,就算能
存下来,一个个比较查询也是不可能的,所以要用hash,这样查询很快,用set存复杂度为,n*logm了,设计hash函数,因为只有 a b c三种字符,所以,可以
用4进制数存,每一位为1 2 3,这样计算hash值后,查询就可以了!
#define N 600005#define MOD 1000000000000000007int n,m;ll pri[N];set<ll> mysets;char str[N];ll getHash(){    ll ans = 0;    for(int i=0;str[i];i++){        ans += (str[i] - 'a' + 1) * pri[i] % MOD;        ans %= MOD;    }    return ans;}bool check(){    ll ans = getHash(),temp;    for(int i=0;str[i];i++){        for(int j=1;j<=3;j++)        if(j !=(str[i] - 'a' + 1)) {           temp = (ans - (str[i] - 'a' + 1) * pri[i] % MOD +  j * pri[i] % MOD + MOD)%MOD;           if(mysets.count(temp))           return true;        }    }    return false;}int main(){    pri[0] = 1;    for(int i=1;i<N;i++){        pri[i] = pri[i-1] * 4 % MOD;    }    while (S2(n,m) != EOF)    {        mysets.clear();        FI(n){            SS(str);            mysets.insert(getHash());        }        FI(m){            SS(str);            if(check())                printf("YES\n");            else                printf("NO\n");        }    }    return 0;}


0 0