哈个希加挂个链表
一个要背的字符串hash函数ELFhash()
mod数取数据最大容量的1.5倍最佳?!
1 #include <set> 2 #include <map> 3 #include <cmath> 4 #include <queue> 5 #include <vector> 6 #include <cstdio> 7 #include <cstdlib> 8 #include <cstring> 9 #include <iostream> 10 #include <algorithm> 11 using namespace std; 12 const int MAXN=150001;//比1e5大的质数 13 struct node{char e[11],f[11];int next;}word[MAXN]; 14 int cnt,hashHead[MAXN];char s[30]; 15 16 int ELFhash(char *key){ 17 unsigned long h=0; 18 for(unsigned long g;*key;h&=~g){ 19 h=(h<<4)+(*key++); 20 g=h&0Xf0000000L; 21 if(g)h^=g>>24; 22 } 23 return h%MAXN; 24 } 25 26 void find(){ 27 int hash=ELFhash(s); 28 for(int i=hashHead[hash];i;i=word[i].next) 29 if(strcmp(s,word[i].f)==0) 30 {printf("%s\n",word[i].e);return;} 31 printf("eh\n"); 32 } 33 34 int main() { 35 for(cnt=1;gets(s)&&s[0]!=‘\0‘;cnt++/*cnt++必须写在外面*/) { 36 sscanf(s,"%s%s",word[cnt].e,word[cnt].f); 37 int hash = ELFhash(word[cnt].f); 38 word[cnt].next=hashHead[hash];//挂表 39 hashHead[hash]=cnt; 40 } 41 while(gets(s))find(); 42 return 0; 43 }
原文:https://www.cnblogs.com/JasonCow/p/12297570.html