一、题目描述
Input Specification:
Output Specification:
Sample Input:
4 4
10 6 4 15
Sample Output:
0 1 4 -
二、解题思路
哈希表的基本操作,涉及到了素数检验,解决冲突用平方探测法(只有正数)。用flag标记是否已经找到位置,用occupy数组标记各个位置是否已经被占用。
三、AC代码
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 10010;
bool occupy[maxn] = {
false};
bool checkPrime(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()
{
int Msize, N, tmp, pos;
scanf("%d%d", &Msize, &N);
while(!checkPrime(Msize))
Msize++;
for(int i=0; i<N; i++)
{
scanf("%d", &tmp);
pos = tmp % Msize;
if(!occupy[pos])
{
printf("%d", pos);
occupy[pos] = true;
}
else
{
bool flag = false;
for(int i=1; i<Msize; i++)
{
if(!occupy[(tmp + i*i)%Msize])
{
flag = true;
pos = (tmp + i*i)%Msize;
occupy[pos] = true;
break;
}
}
if(!flag) printf("-");
else printf("%d", pos);
}
if(i!=N-1) printf(" ");
}
return 0;
}