首页 > 技术文章 > 1456:【例题2】图书管理

lyc-lb-blogs 2021-07-04 21:13 原文

【题目描述】

图书管理是一件十分繁杂的工作,在一个图书馆中每天都会有许多新书加入。为了更方便的管理图书(以便于帮助想要借书的客人快速查找他们是否有他们所需要的书),我们需要设计一个图书查找系统。

该系统需要支持 2 种操作:

add(s) 表示新加入一本书名为 s 的图书。

find(s) 表示查询是否存在一本书名为 s 的图书。
【输入】

第一行包括一个正整数 n,表示操作数。 以下 n 行,每行给出 2 种操作中的某一个指令条,指令格式为:

add s
find s

在书名 s 与指令(add,find)之间有一个隔开,我们保证所有书名的长度都不超过 200。可以假设读入数据是准确无误的。
【输出】

对于每个 find(s) 指令,我们必须对应的输出一行 yes 或 no,表示当前所查询的书是否存在于图书馆内。

注意:一开始时图书馆内是没有一本图书的。并且,对于相同字母不同大小写的书名,我们认为它们是不同的。
【输入样例】

4
add Inside C#
find Effective Java
add Effective Java
find Effective Java

【输出样例】

no
yes

【提示】

数据范围

n≤30000。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;

char op[10];
char book[400];
int n;
const int mod1=1e6+3,mod2=1e6+9,p1=71,p2=79,N=30005;
int tot=0,nxt[N],end[N],poi[mod1+5];

void insert(int x,int y)
{
	nxt[++tot]=poi[x];
	poi[x]=tot;
	end[tot]=y;	
}
void find(int x,int y)
{
	for( register int i=poi[x];i;i=nxt[i])
		{
			if(end[i]==y)
				{
					printf("yes\n");
					return;
				}
			
		}
	printf("no\n");
	return;
}

int main(){
	scanf("%d",&n);
	while(n--){
		scanf("%s",op);
		gets(book);
		int l=strlen(book);
		int s1=0,s2=0;
		for(register int i=0 ;i<l;i++){
			
			s1=(s1*p1+book[i])%mod1;

			s2=(s2*p2+book[i])%mod2;
		}
		if(op[0]=='a')
		{	
			insert(s1,s2);				
		}
		else
		{
			find(s1,s2);	
		}
	}		
	return 0;
}

推荐阅读