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

题目


模板及讲解

哈希表的基本操作
程序实现输入n,m,分别表示有n个数要插入,有m个询问
每个询问包含一个整数,如果在Hash表里,就输出”True.”,否则输出”False.”
|算法讨论|Hash表 学习笔记_第1张图片

#include  
#include  
#include  
#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 (ireturn (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;  
}  

你可能感兴趣的:(算法讨论)