This refers to this article, 11-Hashing 2 Hashing (25 points) I tried to replace the container vector with int v[Tsize]; the same can be AC
error record:
-
int i,p = (N%2)? N+2:N+1;//wrong used int i,p = (p%2)? N+1:N+2 找下一个指数的代码昨天刚写过,这里就犯错两个
- for(i=sqrt(q);i>=2;i–){//Here i>=2 is wrongly written as i>2 to judge whether a number is a prime number, and to judge all numbers between 1 and itself , I ignored 2 here, causing an error, and judged 4 as a prime number
-
if(k==Tsize) cout<<"-";//if的位置放错了 if(i!=N-1) cout<<" "; 这里对if的的位置错误放到了循环内部,但实际上在每一次的for循环,都应该读入一个数,输出一个数。
-
while(k<Tsize){ if(v[pos]==0){ v[pos] = key; cout<<pos; break;//forget this while循环的退出条件总是忘记,当输出pos后就应该退出本次循环了
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<vector>
using namespace std;//dont forget ;
int NextPrime(int N){
if(N==1) return 2;
int i,p = (N%2)? N+2:N+1;//wrong used int i,p = (p%2)? N+1:N+2
while(1){
double q = p;
for(i=sqrt(q);i>2;i--){
if(p%i==0) break;
}
if(i==2) return p;
else p += 2;
}
}
int IsPrime(int N){
int i;
double q = N;
if(N==1) return 0;
else if(N==2) return 1;
else{
for(i=sqrt(q);i>=2;i--){
//这里i>=2错写成i>2
if(N%i==0) return 0;
}
return 1;
}
}
int main(){
int MSize,N,Tsize,pos,temp,i,k;
cin>>MSize>>N;
if(IsPrime(MSize))
Tsize = MSize;
else Tsize = NextPrime(MSize);
vector<int> v(Tsize);
for(i=0;i<Tsize;++i){
v[i] = 0;
}
for(i=0;i<N;++i){
int key;
k = 0;
cin>>key;
pos = key%Tsize;
temp = pos;
while(k<Tsize){
if(v[pos]==0){
v[pos] = key;
cout<<pos;
break;//forget this
}
else{
k++;
pos = (temp+k*k)%Tsize;
}
}
if(k==Tsize) cout<<"-";//if的位置放错了
if(i!=N-1) cout<<" ";
}
return 0;
}