手写哈希
struct my_hash{ //unordered_map long long , int static const int BUFF=524287; static const int EDGE=200010; int fi[BUFF+1],k,ne[EDGE]; long long b[EDGE]; int c[EDGE]; __attribute__((always_inline)) int& operator [](long long x){ if (fi[x&BUFF]){ for (int j=fi[x&BUFF]; j; j=ne[j]) if (b[j]==x) return c[j]; ne[++k]=fi[x&BUFF]; b[fi[x&BUFF]=k]=x; return c[k]; } ne[++k]=0; b[fi[x&BUFF]=k]=x; return c[k]; } void clear(){ memset(c+1,0,k*sizeof(*c)); k=0; memset(fi,0,(BUFF+1)*sizeof(*fi)); } }mpp;
struct my_hash{ //stable in linux but slow static const int BUFF=524287; int fi[BUFF+1]; vector<int> ne,c; vector<long long> b; my_hash(){ ne.emplace_back(0); c.emplace_back(0); b.emplace_back(0); }; __attribute__((always_inline)) int& operator [](long long x){ if (fi[x&BUFF]){ for (int j=fi[x&BUFF]; j; j=ne[j]) if (b[j]==x) return c[j]; fi[x&BUFF]=ne.size(); ne.emplace_back(fi[x&BUFF]); b.emplace_back(x); c.emplace_back(0); return c.back(); } fi[x&BUFF]=ne.size(); ne.emplace_back(0); b.emplace_back(x); c.emplace_back(0); return c.back(); } void clear(){ ne.clear(); b.clear(); c.clear(); memset(fi,0,(BUFF+1)*sizeof(*fi)); } }mpp;
template<class T1,class T2> struct my_hash{ static const int BUFF=524287; static const int EDGE=200010; int fi[BUFF+1],k,ne[EDGE];//wei chu shi hua T1 b[EDGE]; T2 c[EDGE]; __attribute__((always_inline)) T2& operator [](const T1 &x){ int temp=x&BUFF; if (fi[temp]){ for (int j=fi[temp]; j; j=ne[j]) if (b[j]==x) return c[j]; ne[++k]=fi[temp]; b[fi[temp]=k]=x; return c[k]=*(new T2()); }
ne[++k]=0; b[fi[temp]=k]=x; return c[k]=*(new T2()); } void clear(){ k=0; memset(fi,0,(BUFF+1)*sizeof(*fi)); } };
内存不泄漏版
#include <bits/stdc++.h> using namespace std; template<class T1,class T2> struct my_hash{ static const int BUFF=10503465; static const int EDGE=1000010; int fi[BUFF+1],k,ne[EDGE];//wei chu shi hua T1 b[EDGE]; T2 c[EDGE]; __attribute__((always_inline)) T2& operator [](const T1 &x){ int temp=x&BUFF; if (fi[temp]){ for (int j=fi[temp]; j; j=ne[j]) if (b[j]==x) return c[j]; ne[++k]=fi[temp]; b[fi[temp]=k]=x; T2 *p=new T2(); c[k]=*p; delete p; return c[k]; }
ne[++k]=0; b[fi[temp]=k]=x; T2 *p=new T2(); c[k]=*p; delete p; return c[k]; } void clear(){ k=0; memset(fi,0,(BUFF+1)*sizeof(*fi)); } };
另一种版本
struct my_hash{ static const int BUFF=8388607; static const int EDGE=10000010; int fi[BUFF+1],k,ne[EDGE];//wei chu shi hua T1 b[EDGE]; T2 c[EDGE]; __attribute__((always_inline)) T2& operator [](const T1 &x){ int temp=x&BUFF; if (fi[temp]){ for (int j=fi[temp]; j; j=ne[j]) if (b[j]==x) return c[j]; ne[++k]=fi[temp]; b[fi[temp]=k]=x; return c[k]; }
ne[++k]=0; b[fi[temp]=k]=x; return c[k]; } void clear(){ for (int i=1; i<=k; ++i) c[i]=T2(); k=0; memset(fi,0,(BUFF+1)*sizeof(*fi)); } };
特化版比模板的快1/4左右,EDGE是总访问数。