跳到正文

个人记录

关于 STL 库 Hash 的一些优化

ARIS2_0约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年5月20日
篇幅
约 4 分钟
获赞
1

版本

  1. v1当前

知周所众,std::unordered_map 和 __gnu_pbds::gp_hash_table 是两种十分常用的哈希表。

但是,考虑到两种哈希表都能被卡到飞起,我们有必要对其采取优化。

unordered_map 优化

由于 unordered_map 的底层实现是固定模数哈希,可以通过异或上一个数的方式来避免被卡。

定义如下 Hash 函数:

C++
mt19937_64 rnd(chrono::system_clock::now().time_since_epoch().count());
struct Hash{
	ull operator ()(const T1 &x)const{
		static const ull r=rnd();
		return x^r;//执行相当的操作
	}
};
unordered_map<T1,T2,Hash>m;

把 T1 T2 换为自己定义的结构,可以防止卡 unordered_map 的数据。

同时,如果重载了 T1 的 ==,也可以实现 unordered_map 装 pair<int,int> 或者自己写的结构体。

注意随机数前面一定要加 static!

gp_hash_table 优化

首先 gp_hash_table 在不含 <iconv.h> 的环境下,需要包含头文件 <ext/pb_ds/assoc_container.hpp>。

gp_hash_table 不同于 unordered_map,其内部实现是直接模 2162^{16} 的,所以异或没有什么 P 用。

我们考虑使用以下神秘的 Hash 函数:

C++
mt19937_64 rnd(chrono::system_clock::now().time_since_epoch().count());
struct Hash{
	ull operator ()(T1 x)const{
		static const ull s1=rnd(),s2=rnd(),s3=rnd();
        //进行等价操作
		x+=s1;
		x=(x^(x>>33))*s2;
		x=(x^(x>>30))*s3;
		return x;
	}
};
__gnu_pbds::gp_hash_table<T1,T2,Hash>m;

注意这里不要写 ull operator ()(const T1 &x)。

把 T1 T2 换为自己定义的结构,就能愉快地使用 gp_hash_table 了!

当然 unordered_map 也可以用上面这个 Hash 函数。

重载自己写的结构体的方法与 unordered_map 相同。

手写 Hash

最后我们还可以手写 Hash。

这里开了 223≈8×1062^{23}\approx8\times 10^6 的空间,在大部分题目中应该是够用的。

C++
namespace exstd{
    mt19937_64 rnd(chrono::system_clock::now().time_since_epoch().count());
    ull Hash(ull x){
        static const ull s1=rnd(),s2=rnd(),s3=rnd();
        //进行等价操作
        x+=s1;
        x=(x^(x>>33))*s2;
        x=(x^(x>>30))*s3;
        return x;
    }
    const ull LEN=1<<23;
    template<class T1,class T2>
    class ARIS2_0_hash_table{
        private:
        bitset<LEN>have;
        T1 key[LEN];T2 val[LEN];
        int check(const T1 &x){
            int i=Hash(x)&(LEN-1);
            while(have[i] and !(key[i]==x))i=(i+1)&(LEN-1);
            have[i]=1;key[i]=x;
            return i;
        }
        public:
        T2 & operator [] (const T1 &x){return val[check(x)];}
        void erase(T1 x){have[check(x)]=0;}
    };
}
exstd::ARIS2_0_hash_table<ull,ull>m;

要改类型的话,顺带改一下 Hash 函数即可。

但是自己写的 Hash 表不能遍历,这下倒闭了/ll

而且这个在 251 上跑的竟然比优化后的 gp_hash_table 慢!汗流浃背了。

原文