一:题目
给定一系列整型关键字和素数P,用除留余数法定义的散列函数H(Key)=Key将关键字映射到长度为P的散列表中。用线性探测法解决冲突。
输入格式:
输入第一行首先给出两个正整数N(≤1000)和P(≥N的最小素数),分别为待插入的关键字总数、以及散列表的长度。第二行给出N个整型关键字。数字间以空格分隔。
输出格式:
在一行内输出每个整型关键字在散列表中的位置。数字间以空格分隔,但行末尾不得有多余空格。
输入样例:
4 5
24 15 61 88
输出样例:
4 0 1 3
二:思路
利用哈希表原理,进行存储数据,然后处理一个位置冲突问题
三:上码
#include<bits/stdc++.h>
using namespace std;
int main(){
int N,M;
cin >> N >> M;
int array[M];
for( int i = 0; i < M; i++){
array[i] = 10000; //之所以 初始化为这么大 是为了解决 下标为0时,关键值也为0,如果 再出现一个余数为0的数,他本来的下标应为1,
//array[i] = 0; //但如果我们初始化为0的话,他就会出现0 可以拿下方例子进行验证
}
for( int i = 0; i < N; i++){
int temp;
cin >> temp;
int K = 1;
int remainder = temp % M;
while( array[remainder] != 10000 && array[remainder] != temp ){//如果是相同的元素则直接输出其在数组中的下标
remainder = (temp + K)%M;
K++;
}
K = 1;//为下次冲突做准备
array[remainder] = temp;
if( i != N - 1)
cout << remainder << ' ';
else
cout << remainder;
}
}
//4 5
//0 15 61 20

四:失败码
最近老这样,这个是我第一次写的码,测试数据没问题,就是超时了
#include<bits/stdc++.h>
using namespace std;
int main(){
int N,M;
int flag = 0;
cin >> N >> M;
vector<int>v1(M);
vector<int>v2;
for( int i = 0; i < M; i++ ){
v1[i] = -1;
}
for( int i = 0; i < N; i++ ){
int temp;
cin >> temp;
int K = 1;
int remainder = temp%M;
if( v1[remainder] == -1 )
v1[remainder] = temp;
else if (v1[remainder] != temp){
while( remainder < M ){
remainder = (temp + K)%M;
K++;
}
}
v1[remainder] = temp;
if( i != N -1 ){
cout << remainder << ' ';
}else
cout << remainder;
}
}
//5 5
//24 15 61 88 15
加油BOY!


被折叠的 条评论
为什么被折叠?



