POJ 2503 Babelfish <串的哈希>

题目:传送门


分析:串的哈希基础题,采用ELFhash算法。另外这道题很水,用c++STL里的map写就更方便了。


代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;

const int MAXN=1e5+5;
const int MOD=1e5+1;
int cnt;
int hash[MOD];

struct Dic{
	char word1[12];
	char word2[12];
	int next;
}dic[MAXN];

int ELFhash(char *str){  
    unsigned long h = 0;  
    unsigned long x = 0;  
    while (*str){  
        h = (h << 4) + (*str++);
        if ((x = h & 0xF0000000L) != 0){
            h ^= (x >> 24);    
            h &= ~x;  
        }  
    }  
    return h % MOD;  
}

void insert(char *word1,char *word2){
	int key=ELFhash(word2);
	strcpy(dic[cnt].word1,word1);
	strcpy(dic[cnt].word2,word2);
	dic[cnt].next=hash[key];
	hash[key]=cnt++;
}

void trans(char *word){
	int key=ELFhash(word);
	for(int i=hash[key];i!=-1;i=dic[i].next){
		if(strcmp(dic[i].word2,word)==0){
			cout<<dic[i].word1<<endl;
			return ;
		}
	}
	cout<<"eh"<<endl;
}

int main(){
	char word1[12],word2[12],word[12];
	memset(hash,-1,sizeof hash); cnt=0;
	while(true){
		char s=getchar();
		if(s=='\n') break;
		word1[0]=s;
		scanf("%s %s",&word1[1],word2);
		insert(word1,word2);
		getchar();
	}
	while(~scanf("%s",word)){
		trans(word);
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值