1078. Hashing (25)

题目链接: http://www.patest.cn/contests/pat-a-practise/1078
题目:

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 -

分析:
Quadratic probing:二次探测
解这道题要知道二次探测法的公式: hi=(h(key)+i*i)%m 0≤i≤m-1 //即di=i2
                               即探查序列为d=h(key),d+12,d+22,…,等。

AC代码:
#include<stdio.h>
#include<iostream>
using namespace std;
bool isPrime(int x){
 if (x == 1)return false;//测试点1就是用户输入的1,如果没有这一句通不过。
 for (int i = 2; i < x; i++){
  if (x % i == 0){
   return false;
  }
 }
 return true;
}
int findNextPrime(int x){
 while (!isPrime(x)){
  x++;
 }
 return x;
}
int main(){
 freopen("F://Temp/input.txt", "r", stdin);
 int M, N;
 cin >> M >> N;
 if (!isPrime(M)){
  M = findNextPrime(M);
 }
 bool *has = new bool[M];
 int *pos = new int[M];
 for (int i = 0; i < M; i++){
  has[i] = false;
  pos[i] = -1;
 }
 for (int i = 0; i < N; i++){
  int number;
  cin >> number;
  for (int j = 0; j < M; j++){
   if (!has[(number + j * j) % M]){//如果位置没有占用,则分配位置
    pos[i] = (number + j * j)% M ;
    has[(number + j * j)% M] = true;
    break;
   }
  }
 }
 for (int i = 0; i < N; i++){
  if (0 == i){
   if (pos[i] == -1){
    cout << "-";
   }
   else{
    cout << pos[i];
   }
  }
  else{
   if (pos[i] == -1){
    cout << " -";
   }
   else{
    cout << " " << pos[i];
   }
  }
 }
 cout << endl;
 return 0;
}


截图:
1078. Hashing (25)_第1张图片
——Apie陈小旭

你可能感兴趣的:(pat,哈希地址探测)