您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之查找七:线性之哈希表

2017-07-15 08:21 411 查看
Think:

1知识点:哈希表+线性探测法

2反思:哈希表+线性探测法,数组要开大一点?

SDUT题目链接

以下为Wrong Answer代码——数组开小了?

#include <bits/stdc++.h>

using namespace std;

int main(){
int hash[1004], pos[1004];
int n, p, i, k, kk, tp;
while(scanf("%d %d", &n, &p) != EOF){
tp = 0;
memset(hash, -1, sizeof(hash));
for(i = 0; i < n; i++){
scanf("%d", &k);
kk = k % p;
if(hash[kk] == -1){
hash[kk] = k;
}
else {
int add = 0;
int t = kk;
while(hash[t] != -1){
t = (kk + add) % p;
if(hash[t] == k){
break;
}
add++;
}
hash[t] = k;
kk = t;
}
pos[tp++] = kk;
}
for(i = 0; i < n; i++)
printf("%d%c", pos[i], i == n-1? '\n': ' ');
}
return 0;
}

/***************************************************
User name:
Result: Wrong Answer
Take time: 0ms
Take Memory: 224KB
Submit time: 2017-07-14 21:35:33
****************************************************/


以下为Accepted代码

#include <bits/stdc++.h>

using namespace std;

int main(){
int hash[1104], pos[1104];
int n, p, i, k, kk, tp;
while(scanf("%d %d", &n, &p) != EOF){
tp = 0;
memset(hash, -1, sizeof(hash));
for(i = 0; i < n; i++){
scanf("%d", &k);
kk = k % p;
if(hash[kk] == -1){
hash[kk] = k;
}
else {
int add = 0;
int t = kk;
while(hash[t] != -1){
t = (kk + add) % p;
if(hash[t] == k){
break;
}
add++;
}
hash[t] = k;
kk = t;
}
pos[tp++] = kk;
}
for(i = 0; i < n; i++)
printf("%d%c", pos[i], i == n-1? '\n': ' ');
}
return 0;
}

/***************************************************
User name:
Result: Accepted
Take time: 0ms
Take Memory: 228KB
Submit time: 2017-07-14 22:02:25
****************************************************/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息