一个很好的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;
}