|算法讨论|Hash表 学习笔记

来源:互联网 发布:金川公司网络学校 编辑:程序博客网 时间:2024/06/05 12:04

题目


模板及讲解

哈希表的基本操作
程序实现输入n,m,分别表示有n个数要插入,有m个询问
每个询问包含一个整数,如果在Hash表里,就输出”True.”,否则输出”False.”
这里写图片描述

#include<cstdio>  #include<algorithm>  #include<cstring>  #define ms(i,j) memset(i,j, sizeof i);  using namespace std;  const int empt = 100000000;//空的hash表置为inf   const int p = 13;//hash表大小   int A[13];//hash表   void initI()//初始化   {      for (int i=1;i<=p;i++) A[i] = empt;  }  int h(int key)//hash函数   {      return key % p;  }  int posI(int key)//定位,找到一个位置   {      int o = h(key);      int i = 0;      while (i<p&&A[(o+i)%p]!=key&&A[(o+i)%p]!=empt) i++;      return (o+i)%p;  }  void insertI(int key)//插入   {      int x = posI(key);      A[x] = key;  }  bool checkI(int key)//查找   {      int x = posI(key);      if (A[x]==key) return true;       return false;  }  int main()  {      initI();      int n,m;      scanf("%d%d", &n, &m);      for (int i=1;i<=n;i++)       {          int xi;          scanf("%d", &xi);          insertI(xi);      }      for (int i=1;i<=m;i++)       {          int xi;          scanf("%d", &xi);          if (checkI(xi)) printf("True.\n"); else printf("False.\n");      }      return 0;  }  
0 0
原创粉丝点击