poj2503 哈希

    直接哈希就好了。map也能过,注意处理输入。

    这题很坑啊,一直runtime error..

    AC代码:

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std; 
const int maxn=1e5+5;
const int hash_base=100001;
int hash_table[maxn];
struct node{
	char s1[11],s2[11];
	int next;
}val[maxn];
int cur=0;
int ELFhash(char key[]){  
    unsigned long h = 0;  
    unsigned long x = 0;  
    while (*key)  
    {  
        h = (h << 4) + (*key++);  //h左移4位,当前字符ASCII存入h的低四位  
        if ((x = h & 0xF0000000L) != 0)  
        { //如果最高位不为0,则说明字符多余7个,如果不处理,再加第九个字符时,第一个字符会被移出  
            //因此要有如下处理  
            h ^= (x >> 24);  
            //清空28~31位  
            h &= ~x;  
        }  
    }  
    return h % hash_base;  
}  
bool hash_insert(char s1[],char s2[]){
	int h=ELFhash(s2);
	int u=hash_table[h];
	hash_table[h]=cur;
	val[cur].next=u;
	//val[cur++]=node(s1,s2);
	strcpy(val[cur].s1,s1);
	strcpy(val[cur].s2,s2);
	++cur;
	return true;
}
void search(char s[]){
	int h=ELFhash(s);
	int u=hash_table[h];
	while(u!=-1){
		if(strcmp(val[u].s2,s)==0) { //find
			printf("%s\n",val[u].s1);
			return;
		}
		u=val[u].next;
	}
	printf("eh\n"); //not found
}
int main(){
	for(int i=0;i<maxn;++i){
		val[i].next=-1;
	}
	memset(hash_table,-1,sizeof(hash_table));
	char s1[11],s2[11];
	char s[40];
	while(1){
		gets(s);
		if(s[0]=='\0') break;
		sscanf(s,"%s %s",s1,s2);
		hash_insert(s1,s2);
	}
	char u[11];
	while(scanf("%s",u)==1){
		search(u);
	}
	return 0;
}

如有不当之处欢迎指出!

转载于:https://www.cnblogs.com/flyawayl/p/8305489.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值