优雅的字符串哈希写法
如果有CE, 显卡看是不是NT写错模数
using ll = long long;
using ull = unsigned long long;
template<typename hst,hst B,hst M>
struct hash_s{
static hst phs[N];
int len ; hst val;
hash_s(int len_ = 0, hst val_= 0) : len(len_), val(val_){}
static void init(){
phs[0] = 1;
for(int i = 1; i < N; ++i) phs[i] = phs[i - 1] * B % M;
}
hash_s friend operator + (const hash_s& x,const hash_s& y){
return {x.len + y.len, (x.val * phs[y.len] + y.val) % M};
}
friend hash_s operator - (const hash_s& x, const hash_s& y){
return {x.len - y.len, ((x.val - y.val * phs[x.len - y.len]) % M + M) % M};
}
friend bool operator == (const hash_s& x, const hash_s& y){
return x.len == y.len && x.val == y.val;
}
};
template<typename hst,hst B,hst M>
hst hash_s<hst, B, M>::phs[N];
struct hash_m{
using _ht1 = hash_s<ll, 131, 998244353>;
using _ht2 = hash_s<ll, 1145141, 998244853>;
_ht1 h1;
_ht2 h2;
hash_m() = default;
hash_m(int len_, int val_){
h1 = {len_, val_};
h2 = {len_, val_};
}
hash_m(_ht1 h1_, _ht2 h2_){
h1 = h1_;
h2 = h2_;
}
static void init(){
_ht1::init();
_ht2::init();
}
hash_m friend operator +(const hash_m& x, const hash_m& y){
return {x.h1 + y.h1, x.h2 + y.h2};
}
hash_m friend operator -(const hash_m& x, const hash_m& y){
return {x.h1 - y.h1, x.h2 - y.h2};
}
bool friend operator ==(const hash_m& x, const hash_m& y){
return x.h1 == y.h1 && x.h2 == y.h2;
}
};
作者:cdsidi
出处:https://www.cnblogs.com/cdsidi/p/16908062.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】