跳到正文

科技·工程

Hash模版

yh24gys约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年8月26日
收录
2026年10月18日
更新
2026年10月18日
篇幅
约 3 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
mt19937_64 rnd1(chrono::steady_clock::now().time_since_epoch().count());
mt19937 rnd2(time(0));

//字符串Hash 
struct Hash{
	int base = 13331, mod = 1e9 + 9;
	vector<int>h, p;
	void init_hash(string s){
		h.assign(s.length() + 1, 0);
		p.assign(s.length() + 1, 0);
		p[0] = 1;
		for(int i = 0; s[i]; i++){
			p[i + 1] = (p[i] * base) % mod;
			h[i + 1] = (h[i] * base + s[i]) % mod;
		}
	}
	int get_hash(int l, int r){
		return ((h[r] - h[l - 1] * p[r - l + 1]) % mod + mod) % mod;
	}
};

struct Hash_two_mod{
	int base1 = 13331, base2 = 6151, mod1 = 1e9 + 9, mod2 = 1e9 + 7;
	vector<int>h1, h2, p1, p2;
	void init_hash(string s){
		h1.assign(s.length() + 1, 0);
		h2.assign(s.length() + 1, 0);
		p1.assign(s.length() + 1, 0);
		p2.assign(s.length() + 1, 0);
		p1[0] = p2[0] = 1;
		for(int i = 0; s[i]; i++){
			p1[i + 1] = (p1[i] * base1) % mod1;
			p2[i + 1] = (p2[i] * base2) % mod2;
			h1[i + 1] = (h1[i] * base1 + s[i]) % mod1;
			h2[i + 1] = (h1[i] * base2 + s[i]) % mod2;
		}
	}
	pair<int,int> get_hash(int l, int r){
		int res1 = ((h1[r] - h1[l - 1] * p1[r - l + 1]) % mod1 + mod1) % mod1;
		int res2 = ((h2[r] - h2[l - 1] * p2[r - l + 1]) % mod2 + mod2) % mod2;
		return {res1, res2};
	}
};

//集合Hash
struct Hash_set{
	map<int, int>w;
	int hval = 0;
	void add_del(int x){
		if(w.find(x) == w.end()) w[x] = rnd1();//可以用rnd2 
		hval ^= w[x];
	}
	int get_hash(){
		return hval;
	}
}; 

int main(){
	
	return 0;
}
原文