P12201 题解

· · 题解

P12201 题解

个人以为没有蓝题的难度,最多也就绿。

题面

没啥好说的,就是给你一个双哈希的模数和底数,让你 hack 掉它。

思路

根据生日悖论和我们写单哈希的经验表明,随便造一组有 10^5 个字符串,每个字符串长度为 10 是有大概率能卡掉模数在 int 范围内的单哈希,我们可以先将第一个模数和底数用随机的方式卡掉,并且找出冲突的两个,设其为 a,b。

可以发现,假设 x 和 y 哈希冲突了,那 x + x + \cdots + x 和 y + y + \cdots y 也哈希冲突,其中 + 运算符表示将两字符串进行拼接操作。原理很简单,由于 \operatorname{hash}(x) \equiv \operatorname{hash}(y) \pmod p,所以 \operatorname{hash}(x) \cdot (b^{\lvert x \rvert} + 1) \equiv \operatorname{hash}(y) \cdot (b^{\lvert y \rvert} + 1) \pmod p,就是 \operatorname{hash}(x + x) \equiv \operatorname{hash}(y + y) \pmod p。

有了以上条件,就容易了。又根据生日悖论,我们可以进行随机数,如果为奇数,就插个 a,否则插 b,最后看有没有两个随机出的字符串在第二个模数和底数冲突。如果有,则根据上面所述,它们在第一个模数和底数冲突且在第二个模数和底数冲突,即为答案。

代码

#pragma G++ optimize("Ofast")
#pragma G++ optimize("unroll-loops")
#pragma G++ optimize("inline")
#pragma G++ optimize("-ffast-math")
#pragma G++ optimize("-fstrict-aliasing")
#pragma G++ optimize("-funsafe-loop-optimizations")
#include <bits/stdc++.h>
#include <bits/extc++.h>
//#include <windows.h>
#define pque priority_queue
#define fi first
#define se second
#define un unsigned
#define si signed
//#define int long long

using namespace std;
using namespace __gnu_pbds;
using ll = long long;
using LL = unsigned long long;
using Int = unsigned int;
using ld = double;
using Ld = long double;
using pii = pair<int, int>;
using pll = pair<ll, ll>;

const int N = 1e5 + 1;

int m1, b1, m2, b2;
string a, b, x, y, u, v, s[N], t[N];

int strhash(const string &s, int b, int p) {
    int val = 0;
    for (int i = 0; i < s.length(); i++)
        val = (1ll * val * b + s[i] - 'a' + 1) % p;
    return val;
}

int main(){
    //freopen("","r", stdin);
    //freopen("", "w", stdout);
    ios::sync_with_stdio(0), cin.tie(0);
    cin >> b1 >> m1 >> b2 >> m2;
    srand(time(0));
    mt19937 gen(rand());//这是一种随机数
    while(1){
        map<int, int> mp;
        int flag = 0;
        for(int i = 1; i <= (int)1e5; ++i){
            int has = 0;
            for(int j = 1; j <= 10; ++j){
                ll x = gen();
                s[i].push_back('a' + x % 26);
            }
            has = strhash(s[i], b1, m1);
            if(mp.count(has) && s[mp[has]] != s[i]){
                a = s[mp[has]], b = s[i], flag = 1;
                break;
            }
            mp[has] = i;
        }
        if(flag){
            break;
        }
    }
    while(1){
        map<int, int> mp;
        int flag = 0;
        for(int i = 1; i <= (int)1e5; ++i){
            int has = 0;
            for(int j = 1; j <= 10; ++j){
                ll x = gen();
                t[i] += (x % 2 == 0 ? a : b);
            }
            has = strhash(t[i], b2, m2);
            if(mp.count(has) && t[mp[has]] != t[i]){
                x = t[mp[has]], y = t[i], flag = 1;
                break;
            }
            mp[has] = i;
        }
        if(flag){
            break;
        }
    }
    cout << x << '\n' << y;
    return 0;
}

然后的然后,这道水蓝色的题就这么水淋淋的过去了。