1078. 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 (<=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 15Sample Output:
0 1 4 -
题意:二次探测再散列,即平方探测法。先找到一个最接近题目给的m的质数为哈希表长度,然后每个位置的进行二次探测,最多每个位置探测m次
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <functional>
using namespace std;
#define LL long long
const int INF = 0x3f3f3f3f;
int n, m, f[100009], x, vis[100009];
int a[100009];
void init()
{
memset(f, 1, sizeof f);
f[0] = f[1] = 0;
for (int i = 2; i < 100009; i++)
{
if (f[i])
{
for (int j = 2 * i; j < 100009; j += i)
f[j] = 0;
}
}
}
int main()
{
init();
while (~scanf("%d%d", &m, &n))
{
while (!f[m]) m++;
memset(vis, 0, sizeof vis);
for (int i = 1; i <= n; i++)
{
scanf("%d", &x);
int flag = 0;
for (int j = 0; j < m; j++)
{
if (!vis[(x + j * j) % m])
{
vis[(x + j * j) % m] = 1;
printf("%d", (x + j * j) % m);
flag = 1; break;
}
}
if (!flag) printf("-");
printf("%s", i != n ? " " : "\n");
}
}
return 0;
}