## PAT 甲级 1078 Hashing

https://pintia.cn/problem-sets/994805342720868352/problems/994805389634158592

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 ( where

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:

### 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 <bits/stdc++.h>
using namespace std;

const int maxn = 1e4 + 10;
int N, M;
int num[maxn], prime[maxn];
int vis[maxn] = {0};

bool isprime(int x) {
if(x == 2) return true;
if(x <= 1) return false;

for(int i = 2; i * i <= x; i ++) {
if(x % i == 0) return false;
}
return true;
}

void Hash(int x) {
for(int i = 0; i < N; i ++) {
int cnt = (x + i * i) % M;
if(vis[cnt] == 0) {
vis[cnt] = 1;
printf("%d", cnt);
return ;
}
}
printf("-");
}

int main() {
/*memset(prime, 1, sizeof(prime));
for(int i = 2; i * i <= maxn; i ++) {
for(int j = 2; j * i < maxn; j ++)
prime[j * i] = 0;
}*/

scanf("%d%d", &M, &N);
for(int i = 0; i < N; i ++)
scanf("%d", &num[i]);

while(!isprime(M)) M ++;

//    mp.clear();
for(int i = 0; i < N; i ++) {
Hash(num[i]);
printf("%s", i != N - 1 ? " " : "");
}
return 0;
}


二次方探查法   想当一个盲流子

FH

0条评论