题目
思路
先判断原题hash位置有没有被占用,如果被占用,就进行二次平方探查;
代码
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 1e4 + 10;
bool flag[maxn];
bool isPrime(int a){
if(a <= 1) return false;
for(int i = 2; i * i <= a; i ++){
if(a % i == 0) return false;
}
return true;
}
int main()
{
memset(flag, false, sizeof(flag));//初始化
int s, n, t;
scanf("%d%d", &s, &n);
while(isPrime(s) == false) s ++;
for(int i = 0; i < n; i ++){
scanf("%d", &t);
if(flag[t % s] == false) printf("%d", t % s), flag[t % s] = true;
else{
//如果找不到进行平方探查
int step;
for(step = 1; step < s; step ++){
int idx = (t + step * step) % s;
if(flag[idx] == false){
flag[idx] = true;
printf("%d", idx);
break;
}
}
//如果大于size,说明放不下;
if(step >= s) printf("-");
}
if(i != n - 1) printf(" ");
}
system("pause");
return 0;
}