• 哈希 --- 线性探测法


    Constraints

    Time Limit: 1 secs, Memory Limit: 256 MB

    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<cstdio>
    #include<cstring>
    #include<iostream>
    using namespace std;
    int main()
    {
        int n,m;
        int a,b;
        int num[10001];
        memset(num,0,sizeof(num));
        cin>>n>>m;
        while(n--)
        {
            cin>>a;
            b=a%m;
            if(!num[b])
                num[b]=a;
            else
                while(num[b])
                {
                    b++;
                    b%=m;
                }
                num[b]=a;
        }
        for(int i=0;i<m;i++)
        {
            if(!num[i])
                cout<<i<<"#NULL"<<endl;
            else cout<<i<<"#"<<num[i]<<endl;
        }
        return 0;
    }
  • 相关阅读:
    openlayers 聚合效果
    OpenLayers 3 实现轨迹回放
    经纬度和墨卡托互相转换
    OpenLayers 3 给features 添加手势
    OpenLayers 3 实现划线,画点
    C# 在窗体的子线程中创建新窗体
    openlayers 3 读取展示shp文件
    地理信息未来5年规划
    OpenLayers3 实现自定义放大缩小滑块,自定义方向按钮
    2014最后一篇,记ExpandableListViewd的自定义
  • 原文地址:https://www.cnblogs.com/crazyacking/p/3757386.html
Copyright © 2020-2023  润新知