AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

AcWing 840. 模拟散列表 C++    原题链接    简单

作者: 作者的头像   张立斌 ,  2019-10-26 22:05:27 ,  所有人可见 ,  阅读 1222


1


静态链表

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;
}

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息