字符串Hash (BKDRHash)

Problem:

Task: 现在有一个简单的学生管理系统, 要求实现以下几个功能:

1.向名单内添加学生;

2.删除名单内的某个学生;

3.查询某学生是否存在;

Input:

          输入第一行为一个正整数n(1<=n<=100000)表示操作的数目。

           接下来每行为一个正整数x(x=1,2,3)和字符串s,表示操作的类型和学生的姓名,每个学生的姓名长度不超过5。

           x = 1 为插入操作,向名单内增加一个姓名为s的学生。若名单内已有这个学生,则不操作。

           x = 2为删除操作,删除名单内姓名为s的学生, 若此学生不在名单内,则输出“The student does not exist!”;

           x = 3为查询操作,如果姓名为x的学生在名单内,则输出"Yes“,否则输出"No";

Output:

           如果有需要输出的操作,则输出对应的内容并换行。


输入示例:                                 输出示例

5                                                   Yes

1 xx                                               The student does not exist!

3 xx                                               No

2 aaa

2 xx

3 xx


CODE:

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<map>
#include<stack>
#include<queue>
#include<ctime>
#include<cstring>
#include<string>
#define LL __int64
#define INF 0x3f3f3f3f3f
using namespace std;
struct table{
	char *c;
	table *next;
};
struct node{
	table head;
}hash[170000];
char s[100005][6];//指针指向确切存在的地址 ,所以要定义s[][] 
void init()
{
	for(int i=0; i<170000; i++) hash[i].head.next=NULL;
	return ;
}
int gethash(char c[])
{
	int seed = 7;
	LL hash_key=0;
	int len = strlen(c);
	for(int i=0; i<len; i++)
	{
		hash_key = hash_key*seed + c[i]-'A'+1;
	}
	return hash_key;
}
void creat(char c[])
{
	bool query(char c[]);
	if(query(c)) return;
	int hash_key = gethash(c);
	table *p=new table;	
	p->c = c;
	p->next = hash[hash_key].head.next;
	hash[hash_key].head.next = p;
	return ;
}
void del(char c[])
{
	int hash_key = gethash(c);
	table *p=&hash[hash_key].head;
	while(p->next)
	{
		if(!strcmp(p->next->c, c)) break;
		p=p->next;
	}
	if(p->next==NULL) printf("The student does not exist!\n");
	else
	{
		p->next = p->next->next;
	}
	return ;
}
bool query(char c[]) 
{
	int hash_key = gethash(c);
	table *p=hash[hash_key].head.next;
	while(p)
	{
		if(!strcmp(p->c, c)) return true;
		p=p->next;
	}
	return false;
}
int main()
{
	int i,n, m;
	scanf("%d", &n);
	init();
	for(i=0; i<n; i++)
	{
		scanf("%d", &m);
		scanf("%s", s[i]);
		if(m==1) 	  creat(s[i]);
		else if(m==2) del(s[i]);
		else if(m==3) printf("%s\n", (query(s[i]))?"Yes":"No");
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值