PTA string keyword hash map (hash table)

Given a set of keywords and the prime number P String uppercase English letters, the hash function H (Key) method defined by the shift key Key in the last 3 characters mapped to an integer, with each character 5 bit; then I stay in addition to map integers to the length of the hash table P. For example, the string length is inserted into the hash table AZDEG 1009, we mapped the first 26 capital letters to order an integer of 0 to 25; then mapped by shifting it to 3 × 32 ^ 2 + 4 × 32 + 6 = 3206; then obtained according to the length of the table, i.e., a hash map the location of the string.

Please solve squared method to detect when a conflict occurs.

Input formats:

Firstly, a first input line of two positive integers N (≤500) and P (≥2N the minimum prime number), respectively, the length of the total number of keywords to be inserted, and hash table. The second line gives N keyword string, each length of not more than 8, separated by a space therebetween.

Output formats:

Each position of the string output of the hash table of keywords in a row. Between numbers separated by spaces, but the end of the line may not have the extra space.

Sample Input 1:

4 11
HELLO ANNK ZOE LOLI

Output Sample 1:

3 10 4 0

Sample Input 2:

6 11
LLO Anna NNK happening INNK AAA

Output Sample 2:

3 0 10 9 6 1


Secondary detection method:
f ( k e Y ) = ( f ( k e Y ) + d i ) M O D m ( d i = 1 2 , 1 2 , 2 2 , 2 2 , , q 2 , q 2 , q < = m / 2 ) f(key) = (f(key)+di) MOD m (di = 1^2, -1^2, 2^2, -2^2,……, q^2, -q^2, q <= m/2)

Principle hash table almost forgot ...


#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<list>
#include<set>
#include<cmath>
using namespace std;
typedef long long ll;
#define N 100005
int p,n,vis[N];
map<string,int> maps;
	
int main(){
	string str,str1;
	scanf("%d%d",&n,&p);
	for(int j=0;j<n;j++){
		cin >> str;
		if(maps.count(str)){
			if(j==0) cout << maps[str];
			else cout << " " << maps[str];
			continue;
		}
		int len = str.length();
		str1 = str; 
		if(len>=3)
			str1 = str.substr(len-3);
		int pos = 0;
		for(int i=str1.length()-1,k=0;i>=0;i--,k++){
			pos += (str1[i]-'A')*pow(32,k);
		}
		pos = pos%p;
		if(maps[str]==0&&vis[pos]){
			for(int i=1;;i++){
				int di = i*i,tpos = (pos+di)%p;
				if(!vis[tpos]){
					maps[str] = tpos;
					vis[tpos] = 1;
					break;
				}
				else {
					tpos = (pos-di+p)%p;
					if(!vis[tpos]){
						maps[str] = tpos;
						vis[tpos] = 1;
						break;
					}
				}	
			} 
		}	
		else {
			pos %= p;
			maps[str] = pos;
			vis[pos] = 1;
		}
		if(j!=0) cout << " " << maps[str];
		else cout << maps[str];    
	}
	return 0;
}

Published 79 original articles · won praise 37 · views 8884

Guess you like

Origin blog.csdn.net/SinclairWang/article/details/104100093