forked from mpfeifer1/Kattis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcuckoo.cpp
90 lines (77 loc) · 1.59 KB
/
cuckoo.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <bits/stdc++.h>
using namespace std;
map<int,int> reinserted;
vector<int> current;
vector<pair<int,int>> hashes;
bool swap(int n, int old) {
reinserted[n]++;
if(reinserted[n] >= 3) {
return false;
}
int val;
if(hashes[n].first == old) {
val = hashes[n].second;
}
else {
val = hashes[n].first;
}
if(current[val] == -1) {
current[val] = n;
return true;
}
else {
int temp = current[val];
current[val] = n;
return swap(temp,val);
}
}
bool insert(int n) {
if(current[hashes[n].first] == -1) {
current[hashes[n].first] = n;
return true;
}
else if(current[hashes[n].second] == -1) {
current[hashes[n].second] = n;
return true;
}
else {
int temp = current[hashes[n].first];
current[hashes[n].first] = n;
return swap(temp,hashes[n].first);
}
}
void solve() {
reinserted.clear();
hashes.clear();
current.clear();
int n, m;
cin >> m >> n;
hashes.resize(m);
current.resize(n,-1);
// Read in the input
for(int i = 0; i < m; i++) {
cin >> hashes[i].first;
cin >> hashes[i].second;
}
bool works = true;
for(int i = 0; i < m; i++) {
if(!insert(i)) {
works = false;
break;
}
reinserted.clear();
}
if(works) {
cout << "successful hashing" << endl;
}
else {
cout << "rehash necessary" << endl;
}
}
int main() {
int cases;
cin >> cases;
while(cases--) {
solve();
}
}