zoukankan      html  css  js  c++  java
  • hash哈希

    我复习的时候,突然发现没写过hash算法,惊讶!!!赶紧补一下。

    把字符串看成base进制的数。Hash值比较就是为了判断是否有相同的字符串。(base是自己定义的大于26的质数,个人认为大一点比较好)

    下面是代码

    void hash(char a[],int p)
    {
      int l = strlen(a);
      unsigned long long tot;
      for(int i = 0;i < l;i++)
         tot  = (tot * base) + a[i]; //base = 131
      data[p] = tot;
    }

    这是一个简单的一维hash,假如有冲突的话可以用二维哈希来处理冲突(就是再找一个base,每个字符串再求一个对应的hash值)

    来一个例题

    #include<iostream>
    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    using namespace std;
    typedef unsigned long long ull;
    char s[10000];
    ull a[10000];
    int m,k = 1;
    const ull base = 131;
    int haxi(char s[])
    {
        int l = strlen(s);
        ull tot = 0;
        for(int i = 0;i < l;i++)
        {
            tot = tot * base + (s[i] - 'a');
        }
        return tot&0x7fffffff;
    }
    int main()
    {
        cin>>m;
        for(int i = 0;i < m;i++)
        {
            scanf("%s",s);
            a[i] = haxi(s);
        }
        sort(a,a + m);
        for (int i = 1;i < m;i++)
            if (a[i] != a[i - 1])
                k++;
        cout<<k<<endl;
        return 0;
    }

    这个代码就是想知道到底读入了几个不同的字符串,但不要求记录,所以hash变的很合适。

  • 相关阅读:
    python_day16_闭包_装饰器
    高阶函数_递归函数_内置函数
    python_day14_函数_返回值_局部和全局变量
    python_day14_set_回到了python的学习
    grep_sed_awl_vim
    jQuery学习之选择器
    css3之其他的属性
    css3之响应式
    css3之各种布局
    css3之各种变形
  • 原文地址:https://www.cnblogs.com/DukeLv/p/8463630.html
Copyright © 2011-2022 走看看