现在的位置: 首页 > 综合 > 正文

常见的hash函数

2013年12月01日 ⁄ 综合 ⁄ 共 858字 ⁄ 字号 评论关闭

 

转自http://hi.baidu.com/aconly/blog/item/5c82eb76f70f601cb051b952.html

 

字符串的 hash (有许多现成函数,选择合适的就行)

poj 2503

int ELFhash(char *key)             

{

    unsigned long h=0;

    while(*key)

    {

        h=(h<<4)+*key++;

        unsigned long g=h&0Xf0000000L;

        if(g) h^=g>>24;

        h&=~g;

    }

    return h%MOD;

}

数组的 hash (有现成函数)

poj3274

int getkey(int *v,int k)

{

       int i,p=0;

       for(i=1; i<k; i++)

              p=((p<<2)+(v[i]>>4))^(v[i]<<10);

       p = p%prime;

       if(p<0)    p=p+prime;

       return p;

}

全排列的 hash (没有冲突的 hash, 利用全排列与逆序数列一一对应的原理)

poj1077

template <typename T>
size_t PermutationToNumber(const T permutation[], int n)
{
// n不能太大,否则会溢出(如果size_t为32位,则n <= 12)
size_t result = 0;
for (int j = 1; j < n; ++j) {//每一种排列对应一种逆序,每一种逆序对应一个结果
       int count = 0;
       for (int k = 0; k < j; ++k) {
         if (permutation[k] > permutation[j])
            ++count;
       }
       // factorials[j]保存着j!(j的阶乘)
       result += count * factorials[j];
}

return result;
}

 

抱歉!评论已关闭.