哈希表:图书管理

我们来看一下题目:
在这里插入图片描述
不难看出,我们这道题可以直接用库函数中的哈希表来做。
在这之前让我们了解一下有关哈希表的库函数

  1. count(l):返回容器中值为 l 的元素数,如果容器中不存在值为 l 的元素,则返回 0。
    2.emplace(l):向容器中添加新元素,传入的参数会被作为元素值进行插入操作,如果容器中已经存在相同元素,则什么也不做。
    OK呀那么用他俩来实现一下
#include<bits/stdc++.h>
using namespace std;
unordered_set<string> s;
int n;string t,cmd;
int main(){
	cin>>n;getchar();//用于去除add后,和find后的空格
	for(int i=0;i<n;i++){
		cin>>cmd;getline(cin,t);
		if(cmd[0]=='a')s.emplace(t);
		else
			if(s.count(t)==1)cout<<"yes"<<endl; else cout<<"no"<<endl;
	}
	return 0;
}

这时候
有的聪明的同学就会问了
我们改如何在不用库函数的情况下,手打hash表来进行实现呢?
这时候就要请出我们的双hash思想了
我们用代码实现一下:

#include<bits/stdc++.h>
using namespace std;
const int b=13,M=30010;
int n;string t[M],cmd;int hed[1000001],nxt[M];
int h(string a){
	int s=0;
	for (int i=0;i<a.size();i++) s=(s*b+a[i]-'A'+1)%1000001;//此处用来求出一串字符的hash值并取模
	return s;
}
bool insert(int s,int way){
	int v=h(t[s]);
	int u=hed[v];
	while (u){
		if (t[u]==t[s]) return true;
		u=nxt[u];
	}
	if (way==1) return false;
	nxt[s]=hed[v];hed[v]=s;
	return true;
}//此处为链表,因为再取mod后,两值可能存在相等的情况,即hash值冲突,因此要用链表来解决。
int main(){
	cin>>n;getchar();int ii=0;
	for (int i=0;i<n;i++){
		cin>>cmd;getchar();
		getline(cin,t[++ii]);
		if (cmd[0]=='a') insert(ii,0);
		else{
			if (insert(ii,1)) cout<<"yes"<<endl;
			else cout<<"no"<<endl;
		}
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值