7-7 Hashing
分数 25
全屏浏览
切换布局
作者 陈越
单位 浙江大学
The task of this problem is simple: insert a sequence of distinct positive integers into a hash table, and output the positions of the input numbers. The hash function is defined to be H(key)=key%TSize where TSize is the maximum size of the hash table. Quadratic probing (with positive increments only) is used to solve the collisions.
Note that the table size is better to be prime. If the maximum size given by the user is not prime, you must re-define the table size to be the smallest prime number which is larger than the size given by the user.
Input Specification:
Each input file contains one test case. For each case, the first line contains two positive numbers: MSize (≤10
4
) and N (≤MSize) which are the user-defined table size and the number of input numbers, respectively. Then N distinct positive integers are given in the next line. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print the corresponding positions (index starts from 0) of the input numbers in one line. All the numbers in a line are separated by a space, and there must be no extra space at the end of the line. In case it is impossible to insert the number, print "-" instead.
Sample Input:
4 4
10 6 4 15
Sample Output:
0 1 4 -
1.分析
1.判断初始表大小是否为素数,如果用户给定的最大值不是质数,则必须将表的大小重新定义为大于用户给定大小的最小质数。这里要判断MSize为1的情况。
2.当H(key) = key % MSize。当H(key)位置为空时,直接记录并输出。
3.当发生冲突时,即两个关键字具有相同的哈希值H(key),使用二次探测法来寻找下一个位置。next=( H(key) + i*i ) % MSize ,这里i从1到MSize-1。如果next位置有空闲,就记录并输出,否则输出 "-"。
2.代码
#include<iostream>
#include<cmath>
using namespace std;
const int MAX=1e5+10;
int MSize,N,index[MAX],x;
bool check(int t){ //判断是否为素数if(t==1) return false; //判断为1的特殊情况for(int i=2;i<=sqrt(t);i++){if(t%i==0) return false;}return true;
}
int find(int t){ //用二次探测法查找是否有空闲位置int i=1;int m=t;while(i<MSize){ //当i从1到MSize-1if(!index[t]) return t; //找到返回下标else{t=(m+i*i)%MSize;i++;}}return -1; //找不到返回-1
}
int main(){cin>>MSize>>N;while(!check(MSize)) MSize++; //找到最小的素数for(int i=0;i<N;i++){cin>>x;if(!index[x%MSize]){ //如果没冲突就记录输出index[x%MSize]=1;if(i) cout<<" "<<x%MSize;else cout<<x%MSize;}else{x=find(x%MSize); //有冲突就先查找if(x!=-1){ //找到空闲index[x]=1; //记录if(i) cout<<" "<<x; //输出else cout<<x;} else { //没找到空闲,输出"-"cout<<" -";}}}return 0;
}