1. 程式人生 > >hash 【模板】

hash 【模板】

clas ostream sign 模板 快速 space char string lin

          hash

功能:  hash一般用於快速判斷兩個或多個字符串是否匹配。

實現 : 想一想,如果比較兩個數子的話是很方便的很快,那麽我們把整個字符串看成一個大數。

     它是base進制的len位數。但是我只會比較十進制啊,那就轉成10進制,但又太大了(成百上千位啊)

     不得以,我只好請來一個大質數MOD把這些大數映射到一個較小的範圍內比較。

代碼:

#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#include
<math.h> #include<cstdio> using namespace std; #define LL unsigned long long #define MOD 1000000007 #define base 211 LL n,b[20000]; LL get_hash(char s[ ]) { int len=strlen(s); LL ans=0; for(int i=0;i<len;i++) ans=(ans*base + (LL) s[i])%MOD; return ans; } int main() { scanf(
"%lld",&n); char s[60000]; for(int i=1;i<=n;i++) { cin>>s; b[i]=get_hash(s); } }

hash 【模板】