POJ2503(二分,哈希)

大意:给定n(n<=100000)对外文 英文单词 ,给出外文单词求英文单词。

分析:枚举超时用二分。

代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
const int maxn = 100010;
using namespace std;
struct node
{
	char e[60], s[60];
}dic[maxn];
char t[60];
int pos;
int cmp(node a, node b)
{
	return strcmp(a.s, b.s) < 0;
}
int binserch(char *s)
{
	int l = 0, r = pos - 1;
	while (l <= r)
	{
		int mid = (l + r) / 2;
		if (strcmp(dic[mid].s, s) == 0)
			return mid;
		else if (strcmp(dic[mid].s, s) > 0)
			r = mid - 1;
		else
			l = mid + 1;
	}
	return -1;
}
int main()
{
	//freopen("C:\\in.txt", "r", stdin);
	pos = 0;
	char z;
	while (scanf("%s%c", dic[pos].e, &z) != EOF)
	{
		if (z == '\n')
		{
			strcpy(t, dic[pos].e);
			break;
		}
		scanf("%s", dic[pos++].s);
	}
	sort(dic, dic + pos, cmp);
	int num = binserch(t);
	if (num >= 0)
		printf("%s\n", dic[num].e);
	else
		printf("eh\n");
	while (scanf("%s", t) != EOF)
	{
		num = binserch(t);
		if (num >= 0)
			printf("%s\n", dic[num].e);
		else
			printf("eh\n");
	}
	return 0;
}

hash解决:

#include <iostream>
#include <cstdio>
#include <cstring>
const int mm = 100003;
using namespace std;
struct NODE
{
	char english[12];
	char qlish[12];
}dict[mm];
int hashn[mm], nextn[mm];
int ELFhash(char *key)//字符串hash
{
	long long h = 0;
	long long g;
	while (*key)
	{
		h = (h << 4) + *key++;
		g = h & 0xf0000000L;
		if (g)
			h^= g >> 24;
		h &= ~g;
	}
	return h%mm;
}
int main()
{
	//freopen("C:\\in.txt", "r", stdin);
	char ss[30];
	int n = 0;
	memset(hashn, -1, sizeof(hashn));
	while (gets(ss))
	{
		if (sscanf(ss,"%s%s",dict[n].english, dict[n].qlish) != 2)//sscanf从字符串中读进与指定格式相符的数据。
			break;
		else
		{
			int key = ELFhash(dict[n].qlish);//拉链法解决冲突,模拟链表。
			nextn[n] = hashn[key];
			hashn[key] = n;
			n++;
		}
	}
	while (~scanf("%s", ss))
	{
		int i = hashn[ELFhash(ss)];
		while (i != -1)
		{
			if (!strcmp(dict[i].qlish, ss))
				break;
			i = nextn[i];
		}
		if (i == -1)
			printf("eh\n");
		else
			printf("%s\n", dict[i].english);
	}
	return 0;
}



转载于:https://www.cnblogs.com/nickqiao/p/7583398.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值