poj 2503 Babelfish (哈希)

题意: 给出 (key ,demo)两个字符串, 求输入demo的时候, 要输出相应的key, 如果没有key, 就输出"eh";

题解: 简单的哈希处理, 链表处理冲突

code:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn = 1e6+5;
char a[maxn][12], b[maxn][12];
bool vis[maxn];
struct node{
	char *s;
	char *w;
	node *next;
}word[maxn];
int getHashKey(char *s){
	int key=0;
	while(*s != '\0'){
		key = (key*131 + (*s)*151)%maxn;
		s++;
	}
	return key%maxn;
}
void TurnToHash(char *s, char *p){
	int key = getHashKey(s);
	if(vis[key]){
		node *q = new node;
		q->s = s;
		q->w = p;
		q->next=word[key].next;
		word[key].next = q;
	} else {
		word[key].s = s;
		word[key].w = p;
		word[key].next = NULL;
	}
	vis[key] = 1;
}
void query(char *c){
	int key = getHashKey(c);
	if(!vis[key]) {
		printf("eh\n");
		return ;
	}
	node *p = &word[key];
	while(p){
		if(!strcmp(p->s, c)) {
			printf("%s\n", p->w);
			return ;
		}
		p=p->next;
	}
	printf("eh\n");
	return ;
}
int main(){
	//freopen("in.txt","r",stdin);
	memset(vis, 0, sizeof(vis));
	int i=1;
	while(true){
		scanf("%s", a[i]);
		if(getchar()=='\n') break;
		scanf("%s", b[i]);
		TurnToHash(b[i], a[i]);
		i++;
	}
	query(a[i]);
	char t[50];
	while(~scanf("%s", t)){
		if(t[0]=='\0') break; 
		query(t);
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值