A1078. Hashing
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 (<=104) 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 -
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<math.h>
using namespace std;
int hashTB[] = {,}, loca[];
int isPrime(int n){
int sqr = (int)sqrt(1.0 * n);
if(n == )
return ;
for(int i = ; i <= sqr; i++){
if(n % i == )
return ;
}
return ;
}
int main(){
int N, MSize, temp;
scanf("%d%d", &MSize, &N);
if(isPrime(MSize) == ){
for(int i = MSize + ; ; i++){
if(isPrime(i)){
MSize = i;
break;
}
}
}
for(int i = ; i < N; i++){
int find = ;
scanf("%d", &temp);
if(hashTB[temp % MSize] == ){
hashTB[temp % MSize] = temp;
loca[i] = temp % MSize;
}
else{
for(int j = ; j <= MSize; j++){
if(hashTB[(temp + j * j) % MSize] == ){
hashTB[(temp + j * j) % MSize] = temp;
loca[i] = (temp + j * j) % MSize;
find = ;
break;
}
}
if(find == )
loca[i] = -;
}
}
if(loca[] == -)
printf("-");
else printf("%d", loca[]);
for(int i = ; i < N; i++){
if(loca[i] == -)
printf(" -");
else printf(" %d", loca[i]);
}
cin >> N;
return ;
}
总结:
1、Quadratic probing:平方探测法。 当出现碰撞时,采用 (pos + i^2) mod size的方式探测,pos是已经哈希后的结果,而不是key。i的探测范围从1到Msize。
2、判断素数时,不要忽略1不是素数。
最新文章
- JS无刷新分页插件
- C++中智能指针的设计和使用
- Python 统计IIS日志行数
- console.debug()浏览器控制台打印输出 仅仅在支持console的浏览器下打印
- UESTC_Islands 2015 UESTC Training for Data Structures<;Problem J>;
- CentOS 漏洞修补
- SQL SERVER中XML查询:FOR XML指定PATH
- JVM性能调优,GC
- c++第0次作业
- 从零开始系列之vue全家桶(2)安装调试插件vue Devtools
- nexys4ddr数码管动态扫描Verilog例程
- linux虚拟机网络服务问题
- linux下xdebug的安装和配置方法
- Codeforces672D(SummerTrainingDay01-I)
- music cube
- 小组成员及其git链接
- PHPUnit安装
- postgreSQL连接 java接口
- POJ 2350
- ubuntu 安装JDK8