一个很好的HASH函数

一个很好的HASH函数

  后缀数组的一个例子,强大得我什么都不想说了  一个三分查找函数,课上的作业,放这作模板了
一个hash函数,可以部分代替map 自己欣赏了很久  2009-03-30 21:43:00|  分类: ACM/ICPC |  标签: |举报 |字号大
中
小 订阅 
#include<iostream>
#include<utility>
using namespace std;

#define Type1 char* //关键码类型
#define Type2 int //映射类型 类比于map<Type1,Type2> mp;
const int _maxn=84047;//一个质数 727 1621 3673 8167 17881 38891 84047 180511 386117 821647 1742539。。。
struct _Node
{
    pair<Type1,Type2> p;
    _Node * next;
} *head[_maxn]={0};
_Node * _t;
//ELF Hash Function
int hash(char *str)
{
    unsigned int  hash=0;
    unsigned int x=0;

    while(*str)
    {
        hash=(hash<<4)+(*str++);
        if((x=hash & 0xf0000000L)!=0)
        {
            hash^=(x>>24);
            hash &=~x;
        }
    }
    return (unsigned(hash & 0x7fffffff))%_maxn;
}
inline bool EQ(Type1 k1,Type1 k2)//EQ定义相等操作
{
    return !strcmp(k1,k2);
}    
void delHash(_Node * h)//delHash(
{
    if(h->next) delHash(h->next);
    delete h;
}
void initHash()//initHash
{
    for(int i=0;i<_maxn;i++)
    if(head[i]) {delHash(head[i]);head[i]=0;}
}   
const int error=0;//查不到返回error
Type2 getHash(Type1 key)//getHash(
{
    int tmp=hash(key);
    _t=head[tmp];
    while(_t)
    {
        if(EQ((_t->p).first,key)) return (_t->p).second;
        _t=_t->next;
    }    
    return error;
}
void insertHash(pair<Type1,Type2> pp)//insertHash(
{
    int tmp=hash(pp.first);
    _t=head[tmp];
    if(_t==0)
    {
        _Node * tp=new _Node;tp->p=pp;tp->next=0;       
        head[tmp]=tp; return;
    }   
    while(_t->next)
    {
        if(EQ((_t->p).first,pp.first)){(_t->p).second=pp.second;return;}
        _t=_t->next;
    }
    if(EQ((_t->p).first,pp.first)) {(_t->p).second=pp.second;return;}
    _Node * tp=new _Node;tp->p=pp;tp->next=0;_t->next=tp;
    return;
}
//示例
int main()
{
    Type1 key="324235";
    char*  k="324235";
    //initHash
    initHash();
    //insertHash
    insertHash(make_pair(key,4)); //相当于mp[key]=2;,提速在本地修改
    //getHash
    int t=getHash("324235"); // 相当于t=mp[key];
    cout<<t<<endl;
    system("pause");
    return 0;    
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值