unordered_map小教程

· · 科技·工程

这里我会通过我在 oi-wiki 学到的相关知识讲 unordered_map 的用法和防止被卡的方法。

1. 用法

老版本中 unordered_map 在 tr1 中,头文件为

#include<tr1/unordered_map>

设数据结构时要用:

tr1 :: unordered_map<type1,type2>

自 c++11 起,使用 unordered_map 无需引用 tr1,即:
头文件为

#include<unordered_map>

设数据结构时要用:

unordered_map<type1,type2>

其他的同 stl :: map。

自己写哈希函数

假设你需要自己写哈希函数 func 加入 unordered_map,格式如下:

struct func{
    size_t operator()(type1 x)const{
        //在这里写哈希函数内容
    }
};
unordered_map<type1,type2,func>

3.防止被卡

由于 unordered_map 用的模数比较小,所以需要合适的方法先把编号打乱,常见的是 xor_shift,可以使函数变复杂。如果要进一步加强,可以考虑用随机函数,记得在哈希函数初始化时设一个难以被攻破的随机种。版本在 c++11 之前的考虑使用 rand(),随机种设为 time(0),c++11 之后可以考虑真随机 random_device,但由于 random_device 会耗熵池,降低评测机性能,一般将 random_device 的结果作为 mt19937 的随机种,再用 mt19937 获取随机数,如:

struct func{
    long long so;
    func(){
        srand(time(0));
        so = rand() ^ ((rand() << 5) * 0x172837);
    }
    size_t operator()(long long x)const{
        x = x ^ ((x << 3) * so);
        x = x ^ ((x << 5) * (0x9d8f3482));
        x = x ^ ((x >> 4) * (0xe23f3df2));
        return x;
    }
};
tr1 :: unordered_map<ll, bool,func> ex;

和

random_device d;
mt19937 rp(d());
struct func{
    long long so = rp();
    size_t operator()(long long x)const{
        x = x ^ ((x << 3) * so);
        x = x ^ ((x << 5) * (0x9d8f3482));
        x = x ^ ((x >> 4) * (0xe23f3df2));
        return x;
    }
};
unordered_map<ll, bool,func> ex;