卡单哈希(P12200)
相当于生日悖论,有 人,一年有 天。
根据结论,期望随机 次即可。
时间复杂度 ,其中 为你随机的字符串长度。
不要取太小,不然随机性就挂了。
卡双哈希(本题)
显然我们可以用上面的方法卡掉第一组哈希。
然后我们可以随机拼接这两个字符串,可以发现第一组哈希值还是相等,且还是满足生日悖论的性质。
时间复杂度 ,其中 为拼接的次数。
Code
代码中取 。
// linhanmo
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define For(i, st, ed) for (int i = (st); i <= (ed); ++i)
template<typename type> inline void read(type &x) {
int f = 0, ch; while ((ch = getchar()) < 48 || ch > 57) f ^= ch == 45;
x = 0; do x = x * 10 + (ch ^ 48); while ((ch = getchar()) > 47 && ch < 58); f ? x = -x : 0;
}
// Hash 函数
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;
}
mt19937 rnd(random_device{}());
constexpr int T = 30; // L,T
int b1, p1, b2, p2;
string str1, str2, str(T, 0); // str1,str2 Hash 值相同
unordered_map<int, string> mp; // mp[Hash] = String
pair<string, string> hack(int b, int p, const auto &rnd) {
// b 为底数,p 为模数,rnd 表示两个随机方法
mp.clear();
while (true) { // 期望 sqrt p 次
rnd(str); // 随机或随机拼接
int H = strhash(str, b, p); // Hash
// 是否冲突
if (!mp.count(H) || str == mp[H]) mp[H] = str;
else return {str, mp[H]};
}
}
int main() {
read(b1), read(p1), read(b2), read(p2);
// 单 Hash, O(L sqrt(P))
auto [str1, str2] = hack(b1, p1, [](string &str) { for (char &ch : str) ch = rnd() % 26 + 97; }); // 随机
// 双 Hash, O(LT sqrt(P))
auto [ans1, ans2] = hack(b2, p2, [&](string &str) { str.clear(); For(i, 1, T) str += rnd() & 1 ? str1 : str2; }); // 随机拼接
cout << ans1 << '\n' << ans2 << '\n';
return 0;
}