AcWing 840. 模拟散列表 C++
原题链接
简单
作者:
张立斌
,
2019-10-26 22:05:27
,
所有人可见
,
阅读 1222
静态链表
HashSet
class HashSet {
struct Node {
int key;
int next;
};
public:
explicit HashSet(int tableCapacity = 16, int nodeCapacity = 64, double maxFactor = 1.0)
: tableVec(tableCapacity, -1), maxFactor(maxFactor) {
nodeVec.reserve(nodeCapacity);
}
void insert(int key) {
const int hashCode = hashCodeFunc(key) & (tableSize() - 1);
nodeVec.push_back({key, tableVec[hashCode]});
tableVec[hashCode] = nodeSize() - 1;
}
bool find(int key) const {
const int hashCode = hashCodeFunc(key) & (tableSize() - 1);
for (int i = tableVec[hashCode]; i != -1; i = nodeVec[i].next) {
if (key == nodeVec[i].key) {
return true;
}
}
return false;
}
private:
inline int tableSize() const { return tableVec.size(); }
inline int nodeSize() const { return nodeVec.size(); }
static inline uint32_t hashCodeFunc(uint32_t key) { return key * GOLDEN_RATIO; }
static constexpr uint32_t GOLDEN_RATIO = 0x61C88647U;
vector<int> tableVec;
vector<Node> nodeVec;
double maxFactor;
};
constexpr uint32_t HashSet::GOLDEN_RATIO;
main
#include <iostream>
#include <vector>
using namespace std;
int main(void) {
int n, x;
char oper[4];
scanf("%d", &n);
HashSet hashSet(0x100000);
for (int i = 0; i < n; ++i) {
scanf("%1s%d", oper, &x);
if (oper[0] == 'I') {
hashSet.insert(x);
} else if (oper[0] == 'Q') {
puts(hashSet.find(x) ? "Yes" : "No");
}
}
return 0;
}