PAT (Advanced Level) 1078 Hashing (雜湊、平方探測衝突處理Quadratic probing)
阿新 • • 發佈:2018-12-20
記錄下這題是因為注意平方探測的公式是:,其中i = 0,1,2...TableSize
而非先對key取模再加平方。
這題質數範圍不大,不用二分直接掃也不會T。
#include<bits/stdc++.h> using namespace std; int m,n; int cnt; int prime[1300]; void init(){ cnt = 0; for(int i = 2; i <= 10007; ++i){ int flag = 1; for(int j = 2; j <= sqrt(i); ++j){ if(i % j == 0){flag = 0; break;} } if(flag) prime[++cnt] = i; } } void findp(int *p){ int l = 1, r = cnt, mid; while(l <= r){ mid = (l + r) / 2; if(prime[mid] == *p) break; if(prime[mid] > *p) r = mid - 1; else l = mid + 1; } if(*p > prime[mid]) *p = prime[mid+1]; else *p = prime[mid]; } int ht[10010]; int res[10010]; int hashx(int x){ int add = x % m, index = 1; while(index < m){ if(ht[add] == -1){ ht[add] = x; return add; } else{ add = (x + index * index) % m; ++index; } } return -1; } int main(){ init(); scanf("%d%d",&m,&n); findp(&m); int x; memset(ht,-1,sizeof(ht)); for(int i = 0; i < n; ++i){ scanf("%d",&x); res[i] = hashx(x); } printf("%d",res[0]); for(int i = 1; i < n; ++i){ if(res[i] != -1) printf(" %d",res[i]); else printf(" -"); } return 0; }