POJ 2503 Babelfish hash / qsort+ bsearch

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

#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

  功 能: 二分法搜索
  用 法: 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 );
		else
			printf ( "eh\n" );
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值