Application of hash function

Hash

Predecessor: For the number of times each number appears in the N number in the M pre-queried numbers,Space for timeTo reduce the time complexity, mark each element in M ​​with a marking function, and then when inputting in N, directly use the input number as the subscript of the marking function to count the properties of this number.

Definition of hash:

Convert the element through a function (hash function) toInteger, So that the integer can uniquely represent this element.

That is
, the difference in the type of the key that is converted into an integer key through the hash function leads to the difference in the hash function.

When key is an integer

  • 直接定地址法:That is, directly H(key) = key; //The most common and practical hash application
    - 线性变换:H(key) = a*key + b;
  • 平方取中法:The middle bits of the square of the key are used as the hash value
  • 除留余数法:H(key)=key %mod; //More commonly used.
    Note: The table length Tsize must not be less than mod, otherwise it will be out of bounds; and when mod is a prime number, H(key) can cover the range of [0, mod] as much as possible Each number within.
    But this method has an inevitable conflict, that is, it may happen that H(key1) and H(key2) are the same.
    Resolute method:
    • 1. Linear probing method:
      If the position of the subscript H (Key2) in the table is already occupied by H (key1), then check whether the next bit H (key2)+1 is occupied, if not, use this position ; Otherwise, continue to loop and increase by one until you find one that can be used.
    • 2. Square probe method
      . Check the position in the table in sequence: H(key)+1 2 , H(key)-1 2 , H(key)+2 2 H(key)-2 2 ……. If H(key)+K 2 exceeds TSize of the watch manufacturer, then take H(Key)+k 2 modulo the table length.

When key is a string

Method 1:
First convert the character type to an integer type:

int hashchange(char t){
    
      //PAT中1084,题目中需要转化'A'~'Z','a'~'z','_',其中忽略大小写,那么转化的时候只需要看成0-36个数
	if(t<='Z'&&t>='A'){
    
    
		return  t-'A';
	} 
	else if(t<='z'&&t>='a'){
    
    
		return t-'a';
	} 
	else if(t == '_'){
    
    
		return 36;
	}
	else{
    
    
		return 26+t-'0';
	}
}

Then mark the hashlabel[hashchange(s)] = true;

Method 2:
Or label the character data:
the hashlabel is initialized as: bool hashlabel[128] = {false}
and then each existing data is marked.
See example question 2 for details.

Example analysis

PAT 1092 To Buy or Not to Buy (20 points)

Eva would like to make a string of beads with her favorite colors so she went to a small shop to buy some beads. There were many colorful strings of beads. However the owner of the shop would only sell the strings in whole pieces. Hence Eva must check whether a string in the shop contains all the beads she needs. She now comes to you for help: if the answer is Yes, please tell her the number of extra beads she has to buy; or if the answer is No, please tell her the number of beads missing from the string.

For the sake of simplicity, let’s use the characters in the ranges [0-9], [a-z], and [A-Z] to represent the colors. For example, the 3rd string in Figure 1 is the one that Eva would like to make. Then the 1st string is okay since it contains all the necessary beads with 8 extra ones; yet the 2nd one is not since there is no black bead and one less red bead.

Figure 1

Input Specification:
Each input file contains one test case. Each case gives in two lines the strings of no more than 1000 beads which belong to the shop owner and Eva, respectively.

Output Specification:
For each test case, print your answer in one line. If the answer is Yes, then also output the number of extra beads Eva has to buy; or if the answer is No, then also output the number of beads missing from the string. There must be exactly 1 space between the answer and the number.

Sample Input 1:
ppRYYGrrYBR2258
YrR8RrY
Sample Output 1:
Yes 8
Sample Input 2:
ppRYYGrrYB225
YrR8RrY
Sample Output 2:
No 2

题意:Xiaohong wants to buy some beads to make a string of beads she likes. The bead sellers had a lot of colorful beads, but they refused to break up any of them. So we need to help her solve how many extra beads she has; if not, then tell her how many beads are missing~

Code

#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
using namespace std;
int hashchange(char t){
    
    
	if(t<='Z'&&t>='A') return t-'A';
	else if(t<='z'&&t>='a') return 26+t-'a';
	else  return 52+t-'0';
} 
int hashlabel[128] = {
    
    0};
string a,b;
int main(){
    
    
	cin>>a;
	cin>>b;
	sort(a.begin(),a.end());
	sort(b.begin(),b.end());
	int id;
	for(int i=0;i<b.size();i++){
    
    
		id = hashchange(b[i]);
		hashlabel[id] += 1;
	}
	int extra = 0;
	for(int i=0;i<a.size();i++){
    
    
		id = hashchange(a[i]);
		if(!hashlabel[id]) extra++;
		else{
    
    
			hashlabel[id]--;
		}
	}
	int lack = hashlabel[hashchange(b[0])];
	for(int i=1;i<b.size();i++){
    
    
		id = hashchange(b[i]);
		if(id == hashchange(b[i-1])) continue;
		lack += hashlabel[id];  
	}
	if(lack) printf("No %d\n",lack);
	else printf("Yes %d\n",extra);
	return 0;
}

PAT1050 String Subtraction (20 points)

Given two strings S​1 and S​2 , S=S​1 −S​2​​ is defined to be the remaining string after taking all the characters in S2 from S​1​​ . Your task is simply to calculate S​1​​ −S​2 for any given strings. However, it might not be that simple to do it fast.

Input Specification:
Each input file contains one test case. Each case consists of two lines which gives S1 ​​ and S​2 ​​ , respectively. The string lengths of both strings are no more than 104 . It is guaranteed that all the characters are visible ASCII codes and white space, and a new line character signals the end of a string.

Output Specification:
For each test case, print S​1−S​2 in one line.

Sample Input:
They are students.
aeiou
Sample Output:
Thy r stdnts
题意.: Given two strings, delete all the characters that appeared in the second string in the first string and output

Code

#include <iostream>
#include <string>
using namespace std;
string s1,s2;
bool hashlabel[128] = {
    
    false};

int main(){
    
    
	getline(cin,s1);
	getline(cin,s2);
	for(int i=0;i<s2.size();i++){
    
    
		hashlabel[s2[i]] = true;
	}
	for(int i=0;i<s1.size();i++){
    
    
		if(!hashlabel[s1[i]]) cout<<s1[i]; 
	}
	cout<<endl;
	return 0;
}

Test Questions PAT Level B 1005 Continue (3n+1) Conjecture (25 points)

Callatz conjecture:
For any positive integer n, if it is even, cut it in half; if it is odd, cut (3n+1) in half. This has been repeated repeatedly, and finally n=1 must be obtained at a certain step.
When we verify Karaz’s conjecture, in order to avoid repeated calculations, we can record every number encountered in the recursion process. For example, when verifying n=3, we need to calculate 3, 5, 8, 4, 2, 1, then when we verify n=5, 8, 4, 2, we can directly determine the Karaz conjecture There is no need to repeat the calculation, because these 4 numbers have been encountered during the verification of 3. We call 5, 8, 4, and 2 the numbers "covered" by 3. We call a certain number n in a sequence "key number" if n cannot be covered by other numbers in the sequence.

Now given a series of numbers to be verified, we only need to verify a few of the key numbers, and there is no need to repeat the verification of the remaining numbers. Your task is to find these key numbers and output them in descending order.

输入格式:
Each test input contains 1 test case, the first line gives a positive integer K (<100), the second line gives K different values ​​of positive integers n (1<n≤100) to be verified , Separated by spaces between numbers.

输出格式:
The output of each test case occupies one line, and the key figures are output in descending order. The numbers are separated by a space, but there is no space after the last number in a line.

输入样例:
6
3 5 6 7 8 11
输出样例:
7 6

Code

#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int n ,ipt[110];
int hashtable[10000] = {
    
    0}; 
int main(){
    
    
	scanf("%d",&n);
	int  t;
	for(int i=0;i<n;i++){
    
    
		scanf("%d",&ipt[i]);
		t = ipt[i];
		while(t!=1){
    
    
			if(t%2==0) t = t/2;
			else t = (t*3+1)/2;
			hashtable[t] = 1;				
		}
	}
	vector <int> ans;
	for(int i=0;i<n;i++){
    
    
		if(hashtable[ipt[i]]==0)  ans.push_back(ipt[i]);
	}	
	sort(ans.begin(),ans.end());
	for(int i=ans.size()-1;i>=0;i--){
    
    
		if(i!=ans.size()-1) cout<<" ";
		cout<<ans[i];
	}
	return 0;
}

Encourage
Check in on the fifteenth day, come on. ヾ(◍°∇°◍)ノ゙
Today’s sentiment: I don’t like appearances and expressions.

Guess you like

Origin blog.csdn.net/qq_43992949/article/details/106430486