POJ 2503 Babelfish hash / qsort+ bsearch

来源:互联网 发布:树达学院教务网络系统 编辑:程序博客网 时间:2024/06/06 11:53

题意:先输入字典,然后查词。(以输入空格为界)
题解:别忘了字符串二分查找

#include <cstring>#include <iostream>using namespace std;#define prime 100003struct Union{char eng[11], fore[11];} p[100001];struct node{int id;bool flag;} hash[prime][10];int get_hash(char *str) //这个函数怎么推还真不知道{      int h = 0;      while(*str)      {          h = (h << 4) + *str++;          int g = h & 0xf0000000L;          if(g) h ^= g >> 24;          h &= ~g;      }      return h % prime;  }int main(){char str[100];int j, sum, mark, index, id = -1;memset(hash,NULL,sizeof(hash));while ( gets(str) && str[0] != 0 ){++id;j = sum = 0;sscanf( str,"%s%s", p[id].eng, p[id].fore);index = get_hash(p[id].fore);while ( hash[index][j].flag == true ) ++j;hash[index][j].id = id;hash[index][j].flag = true;}while ( scanf("%s",str) != EOF ){j = mark = 0;index = get_hash(str);while ( hash[index][j].flag  != false ){if ( strcmp ( p[ hash[index][j].id ].fore, str ) == 0 ){mark = true;printf("%s\n",p[ hash[index][j].id ].eng );break;}++j;}if ( !mark )printf("eh\n");}return 0;}

 
学习下二分查找。
函数名: bsearch

  功 能: 二分法搜索
  用 法: void *bsearch(const void *key, const void *base, size_t *nelem, size_t width, int(*fcmp)(const void *, const *));
  语法:
  #include <stdlib.h> void *bsearch( const void *key, const void *buf, size_t num, size_t size, int (*compare)(const void *, const void *) );
  参数:第一个:要查找的关键字。第二个:要查找的数组。第三个:指定数组中元素的数目。第四个:每个元素的长度(以字符为单位)。第五个:指向比较函数的指针。
  功能: 函数用折半查找法在从数组元素buf[0]到buf[num-1] 匹配参数key。如果函数compare 的第一个参数小于第二个参数,返回负值;如果等于返回零值;如果大于返回正值。数组buf 中的元素应以升序排列。函数bsearch()的返回值是指向匹配项,如果没有发现匹配项,返回NULL。
#include <cstdlib>#include <cstring>#include <iostream>using namespace std; struct node{char eng[11], fore[11];} a[100001];int cmp1 ( const void* x, const void* y ){return strcmp( ((node*)x)->fore, ((node*)y)->fore );}int cmp2 ( const void* x, const void*y ){return strcmp( (char*)x, ((node*)y)->fore );}int main(){int id = 0;char str[50];node *p;while ( gets(str) && str[0] != 0 )sscanf( str, "%s%s", a[id].eng, a[id++].fore );qsort(a,id,sizeof(node),cmp1);while ( scanf("%s",str) != EOF ){p = (node*)bsearch ( str, a, id, sizeof(node), cmp2 );if ( p )printf ( "%s\n", p->eng );elseprintf ( "eh\n" );}return 0;}




原创粉丝点击