• sicily 1004. 简单哈希


    Description

     使用线性探测法(Linear Probing)可以解决哈希中的冲突问题,其基本思想是:设哈希函数为h(key) = d, 并且假定哈希的存储结构是循环数组则当冲突发生时继续探测d+1, d+2…, 直到冲突得到解决

    例如现有关键码集为 {477291116922283}

    设:哈希表表长为m=11;哈希函数为Hash(key)=key mod 11;采用线性探测法处理冲突。建哈希表如下:

     

    0

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    22

     

    47

    92

    16

    3

    7

    29

    8

     

     

    现在给定哈希函数为Hash(key)= key mod m,要求按照上述规则使用线性探测法处理冲突.要求建立起相应哈希表,并按要求打印。

    Input

     仅有一个测试用例1行为整数nm1 <= n, m <= 10000), n代表key的总数, m代表哈希表的长度并且令哈希函数为Hash(key) = key mod m.

    接下来n行,每行一个整数,代表一个keyKeykey两两不相同 ( 0 <= key <= 10, 000)

    Output

     输出建立好的hash表,比如下表

    0

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    22

     

    47

    92

    16

    3

    7

    29

    8

     

     

    应输出

    0#11

    1#22

    2#NULL

    3#47

    4#92

    5#16

    6#3

    7#7

    8#29

    9#8

    10#NULL

    Sample Input

    3 5
    1
    5
    6

    Sample Output

    0#5
    1#1
    2#6
    3#NULL
    4#NULL

    第一次交的时候没有注意到“循环数组”。

    以下是代码:

    #include <iostream>
    using namespace std;
    
    int main() {
        int n, m;
        cin>>n>>m;
        int l = m;
        int hash[m];
        for (int i = 0; i < m; i++) hash[i] = -1;
        for (int i = 0; i < n; i++) {
            int num;
            cin>>num;
            int pos = num % m;
            while (hash[pos] != -1) pos = (pos+1) % m;     // %m to make the array a cycle
            hash[pos] = num;
        }
        for (int i = 0; i < m; i++) {
            cout<<i<<'#';
            if (hash[i] == -1) cout<<"NULL"<<endl;
            else cout<<hash[i]<<endl;
        }
        return 0;
    }
  • 相关阅读:
    DataGridView 复选框 操作大全
    ClickOnce 创建桌面快捷方式
    测量程序经过的时间
    C# Js 时间格式化问题
    MVC 漫长之路(一)
    SQL 查一年内的数据
    DataRow对象的RowState和DataRowVersion属性特点
    iOS打开百度地图、高德地图导航
    NSURLCache 和 NSCache 的区别
    MagicalRecord的使用(第三方库实现的数据库)
  • 原文地址:https://www.cnblogs.com/zmj97/p/6262345.html
Copyright © 2020-2023  润新知