hash - 图书管理 - 一本通 2.1 例 2
题目描述
图书管理是一件十分繁杂的工作,在一个图书馆中每天都会有许多新书加入。为了更方便的管理图书(以便于帮助想要借书的客人快速查找他们是否有他们所需要的书),我们需要设计一个图书查找系统。
该系统需要支持 2 种操作:
add(s) 表示新加入一本书名为 s 的图书。
find(s) 表示查询是否存在一本书名为 s 的图书。
输入格式
第一行包括一个正整数 ,表示操作数。 以下 行,每行给出 2 种操作中的某一个指令条,指令格式为:
add s
find s
在书名 s 与指令(add,find)之间有一个隔开,我们保证所有书名的长度都不超过 。可以假设读入数据是准确无误的。
输出格式
对于每个 find(s) 指令,我们必须对应的输出一行 yes 或 no,表示当前所查询的书是否存在于图书馆内。
注意:一开始时图书馆内是没有一本图书的。并且,对于相同字母不同大小写的书名,我们认为它们是不同的。
输入
4
add Inside C#
find Effective Java
add Effective Java
find Effective Java
输出
no
yes
思路:1,使用map容器直接标记。2,用双哈希之后加vector容器。
#include <map>
#include <string>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
map<string, int>p;
int main() {
int n;
char a[10], b[210];
scanf("%d", &n);
while (n--) {
scanf("%s", a);
gets(b);
if (strcmp(a, "add") == 0)
p[b] = 1;
else {
if (p[b])
printf("yes\n");
else
printf("no\n");
}
}
}
#include<vector>
#include<string.h>
#include<iostream>
using namespace std;
int mod1=1e5+3,mod2=1e5+7;
const int N=1e5+10;
vector<int>v[N];
int find(int a,int b)
{
for(int i=0;i<v[a].size();i++)
if(v[a][i]==b)
return 1;
return 0;
}
int main()
{
char a[9],p[400];
int t,i,l,b1=133,b2=167;
cin>>t;
while(t--)
{
cin>>a;
gets(p);
l=strlen(p);
int s1=0,s2=0;
for(i=0;i<l;i++)
{
s1=(s1*b1+p[i])%mod1;
s2=(s2*b2+p[i])%mod2;
}
if(a[0]=='a') v[s1].push_back(s2);
else
{
if(find(s1,s2)) cout<<"yes"<<endl;
else cout<<"no"<<endl;
}
}
}

浙公网安备 33010602011771号