hdu1880 hash算法学习

本题用的是bkdr算法,传说中java内置的hash就是这个实现的


unsigned int BKDRHash(char*str) 
{ 
    unsigned int seed=131 ;// 31 131 1313 13131 131313 etc..  
    unsigned int hash=0 ; 
     
    while(*str) 
    { 
        hash=hash*seed+(*str++); 
    } 
     
    return(hash % M); 
} 

这题我木有A,题解也没咋看懂,虽然网上都说该题很水,,附上保存防丢失。。

//bkdr hash模板
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
const int MAX=210000;
const int mod=100007;

struct Node{
	Node* ne;
	char st[81];
}hash[MAX],*h[mod],*cur;

unsigned int BKDHash(char* s){
	unsigned int seed=131;
	unsigned int ret=0;

	while(*s){
		ret=ret*seed+*s++;
	}

	return (ret&0x7FFFFFFF)%mod;
}
int getId(char* s){
	int code=BKDHash(s);
	Node* ptr=h[code];

	while(ptr){
		if(strcmp(ptr->st,s)==0){
			return ptr-hash;
		}else{
			ptr=ptr->ne;
		}
	}
	strcpy(cur->st,s);
	cur->ne=h[code];
	h[code]=cur++;
	return cur-hash-1;
}

int find(char* s){
	int code=BKDHash(s);
	Node* ptr=h[code];

	while(ptr){
		if(strcmp(ptr->st,s)==0){
			return ptr-hash;
		}else{
			ptr=ptr->ne;
		}
	}
	return -1;
}

int main(){
	char s[100],*p;
	int id,n;

	cur=hash;
	memset(h,0,sizeof(h));
	while(scanf("%s",s),s[0]!='@'){
		getId(s);
		getchar();
		gets(s);
		getId(s);
	}
	scanf("%d",&n);
	gets(s);
	while(n--){
		gets(s);
		id=find(s);
		if(id==-1){
			puts("what?");
		}else{
			p=hash[id^1].st;
			if(p[0]!='['){
				puts(p);
			}else{
				p++;
				while(*p!=']'){
					putchar(*p++);
				}
				puts("");
			}
		}
	}

	return 0;
}


对hash算法有兴趣的话,这里很全,,http://blog.csdn.net/hqd_acm/article/details/5901955


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值