POJ2503
这是一道关于搜索的题,hash,需要用到一个字符串散列函数
1 #include<stdio.h> 2 #include<string.h> 3 #include<stdlib.h> 4 #define M 100003 // 槽数,最好用素数 5 struct node{ 6 int hash; 7 struct node *next; 8 }*link[M]={NULL}; 9 char word[100000][11],dialect[100000][11]; 10 11 12 int ELFhash(char *key)// UNIX 系统ELF字符串散列函数 13 { 14 unsigned long h=0,g; 15 while (*key) 16 { 17 h=(h << 4) + *key++;//h左移四位,当前字符ascii码存入低四位 18 g=h & 0xf0000000L; 19 if (g)//如果最高位不等于0,则说明字符多余7个,如果不处理,再加第九个字符时,第一个字符会被移出,所以要如下处理 20 h ^= g >> 24;//清空28~31位 21 h &= ~g; 22 } 23 return h % M; 24 } 25 26 int main() 27 { 28 char str[50]; 29 int n=0; 30 while(1) 31 { 32 int count=0; 33 int flag=0; 34 while(1) 35 { 36 char ch; 37 ch=getchar(); 38 if(ch=='\n') {flag=1;break;} 39 if(ch!=' ') word[n][count++]=ch; 40 else 41 { 42 word[n][count]='\0'; 43 break; 44 } 45 } 46 if(flag==1) break; 47 count=0; 48 while(1) 49 { 50 char ch; 51 ch=getchar(); 52 if(ch!='\n') dialect[n][count++]=ch; 53 else 54 { 55 dialect[n][count]='\0'; 56 break; 57 } 58 } 59 int index=ELFhash(dialect[n]); 60 node *p=(struct node* )malloc(sizeof(struct node)); 61 p->next=link[index];//第一次这里是null 62 p->hash=n; 63 link[index]=p; 64 n++; 65 } 66 while(scanf("%s",str)!=EOF) 67 { 68 int index=ELFhash(str); 69 node *p=link[index]; 70 while(p!=NULL) 71 { 72 if(strcmp(str,dialect[p->hash])==0) 73 { 74 break; 75 } 76 p=p->next; 77 } 78 if(p==NULL) 79 printf("eh\n"); 80 else 81 printf("%s\n",word[p->hash]); 82 } 83 return 0; 84 }
。。。。。