因爲輸入反了所以WA了好多次... 真的太困了貼完睡覺。
二次探查法都忘記是什麼了,原來還有不能被插入的情況.. 等到真的要去找工作的時候再認真念一念書吧~
1 #include <vector> 2 #include <iostream> 3 #include <cmath> 4 5 using namespace std; 6 7 bool is_prime(int num){ 8 if (num == 1) 9 return false; 10 if (num == 2) 11 return true; 12 13 int sqr = sqrt(num); 14 15 if (num % 2 == 0) 16 return false; 17 18 for (int i = 3; i <= sqr; i += 2){ 19 if (num % i == 0) 20 return false; 21 } 22 23 return true; 24 } 25 26 int main(){ 27 int n, table_size; 28 29 cin >> table_size >> n; 30 31 while (!is_prime(table_size)) 32 table_size++; 33 34 vector<bool> hash_table(table_size, false); 35 vector<int> rec_res(n, -1); 36 37 for (int i = 0; i < n; i++){ 38 int num; 39 cin >> num; 40 41 for (int j = 0; j < table_size; j++){ 42 int idx = (num + j * j) % table_size; 43 44 if (!hash_table[idx]){ 45 hash_table[idx] = true; 46 rec_res[i] = idx; 47 48 break; 49 } 50 } 51 } 52 53 for (int i = 0; i < rec_res.size() - 1; i++){ 54 if (rec_res[i] != -1) 55 cout << rec_res[i] << " "; 56 else 57 cout << "-" << " "; 58 } 59 60 if (rec_res[rec_res.size() - 1] != -1) 61 cout << rec_res[rec_res.size() - 1] << endl; 62 else 63 cout << "-" << endl; 64 }