数据结构与算法题目集(中文)7-43 字符串关键字的散列映射 (25分) (哈希平方探测法)

1.题目

给定一系列由大写英文字母组成的字符串关键字和素数P,用移位法定义的散列函数H(Key)将关键字Key中的最后3个字符映射为整数,每个字符占5位;再用除留余数法将整数映射到长度为P的散列表中。例如将字符串AZDEG插入长度为1009的散列表中,我们首先将26个大写英文字母顺序映射到整数0~25;再通过移位将其映射为3×32​2​​+4×32+6=3206;然后根据表长得到,即是该字符串的散列映射位置。

发生冲突时请用平方探测法解决。

输入格式:

输入第一行首先给出两个正整数N(≤500)和P(≥2N的最小素数),分别为待插入的关键字总数、以及散列表的长度。第二行给出N个字符串关键字,每个长度不超过8位,其间以空格分隔。

输出格式:

在一行内输出每个字符串关键字在散列表中的位置。数字间以空格分隔,但行末尾不得有多余空格。

输入样例1:

4 11
HELLO ANNK ZOE LOLI

输出样例1:

3 10 4 0

输入样例2:

6 11
LLO ANNA NNK ZOJ INNK AAA

输出样例2:

3 0 10 9 6 1

2.题目分析

 1.二次出现的字符串直接输出位置而不重新放置

2.字符串的长度有可能小于3

3.注意平方探测的方法:先正后负

3.代码

#include<iostream>
#include<unordered_map>
#include<string>
#include<cstring>
using namespace std;
int visited[2000] = {0};
int main()
{
	int n, p,u;
	cin >> n >> p;
	string temp;
	int number = 0;
	unordered_map<string, int>list;
	for (int i = 0; i < n; i++)
	{
		number = 0;
		cin >> temp;
		if (list.count(temp))
		{
			cout << " " << list[temp];
			continue;
		}
		if (temp.length() == 1)
			number = temp[0] - 65;
		else if (temp.length() == 2)
			number = 32 * (temp[0] - 65) + (temp[1] - 65);
		else
			number = 32 * 32 * (temp[temp.length() - 3] - 65) + 32 * (temp[temp.length() - 2] - 65) + (temp[temp.length() - 1] - 65);
		
		for (int j = 0; j < p; j++)
		{
			u = (number + j*j) % p;
			if(!visited[u])
			{
				list[temp] = u;
				visited[u] = 1;
				if (i == 0)cout << u;
				else cout << " " << u;
				break;
			}
				u = (number - j*j) % p;
				if (!visited[u])
				{
					list[temp] = u;
					visited[u] = 1;
					if (i == 0)cout << u;
					else cout << " " << u;
					break;
				}
		}
	
	}
	return 0;
}

 

posted @ 2020-02-10 16:07  Jason66661010  阅读(368)  评论(0)    收藏  举报