哈希算法之一

//poj 2503 Babelfish 

#include
<iostream> //ELFhash函数是对字符串的散列
#include <string>
using namespace std;
#define M 1000000
//M如果较小则不能很好地避免冲突,解决冲突需要更多的时间,会TLE,比如200000 当然不能过大,会MLE,比如10000000
//M取适合的值,既可以避免hash开得太大,同时又可以减少冲突
string hash[M],res[M];
int ELFHash(string str) //ELFhash函数
{
int h = 0;
int x = 0;
for(int i=0;i<str.size();++i)
{
h
= (h << 4) + (str[i]);
if ((x = h & 0xF0000000L) != 0)
{
h
^= (x >> 24);
h
&= ~x;
}
}
return h % M;
}

int main()
{

string str,e,f,s;
int ind;
while(getline(cin,str))
{
if(str.size()==0)
break;
int pos=str.find(' ');
e.assign(str,
0,pos); //添加从下标[0]开始的pos个字符
f.assign(str,pos+1,str.size()-1-pos);

ind
=ELFHash(f);
while(hash[ind]!="")
ind
=(ind+1)%M;
hash[ind]
=f;
res[ind]
=e;
}
while(cin>>s)
{
ind
=ELFHash(s);
if(hash[ind]=="")
cout
<<"eh\n";
else
{
while(hash[ind]!=s)
ind
=(ind+1)%M; //开放地址法 线性探查法
cout<<res[ind]<<endl;
}
}
return 0;
}

  

posted on 2011-08-22 15:01  sysu_mjc  阅读(159)  评论(0编辑  收藏  举报

导航