Hashing (25)

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.

输入描述:
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.

输出描述:
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.

输入例子:
4 4
10 6 4 15

输出例子:
0 1 4 -


大意
给出哈希表的大小N 和 M个 正整数,首先求比N大的最小质数,然后假设给出的M个数插入到这个质数为大小的哈希表,并输出
每个数在这个哈希表的位置,即:数%哈希表的大小,若没有位置可以插入则输出“-”。

分析
问题分两步,首先求求出比N大的最小质数,简单暴力即可。后面能够做的关键是熟悉哈希表的原理和什么是Quadratic probing

MYCODE

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<map>
#include<math.h>
using namespace std;
bool isprim(int n){
	if (n < 2) return false;
	for (int i = 2; i < sqrt(n) + 1; i++){
		if (!(n%i)) return false;
	}
	return true;
}
bool ibmap[10009];
int main(){
	int size, n, t;
	cin >> size >> n;
	while (!isprim(size)) size++;
	while (n--){
		cin >> t;
		bool find = false;
		int mod = t%size;
		for (int i = 0; i < size; i++) {
			int tmp = (mod + i * i) % size;
			if (!ibmap[tmp]){
				cout << tmp;
				ibmap[tmp] = true;
				find = true;
				break;
			}
		}
		if (!find) cout << "-";
		cout << (n==0 ? "\n" : " ");
	}
	return 0;
}

随笔
这道题,真的将我难倒了,看题目以为是求余表的大小,被占用了则输出“-”,否则输出求余后的数。但是结果只有样例通过了。
在参考过解题报告后才发现原来当哈希表插入值时,若 x % m 被占用则会采用特定的方法寻找下一个位置,然后题目中说到的Quadratic probing 就是其中一种方法,平方弹测法。都怪平时没有打好理论基础,其实ACM或各样算法测试考察的不仅是解答问题的能力,最根本的是对各种数据结构的原理,实现,和算法思想的理解。

发布了90 篇原创文章 · 获赞 31 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/BlackCarDriver/article/details/96201074
今日推荐