题意:先输入字典,然后查词。(以输入空格为界)
题解:别忘了字符串二分查找
#include <cstring>
#include <iostream>
using namespace std;
#define prime 100003
struct 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
#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 );
else
printf ( "eh\n" );
}
return 0;
}