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

来源:互联网 发布:js domloaded 编辑:程序博客网 时间:2024/06/13 00:46

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 AnswerTake time: 0msTake Memory: 224KBSubmit 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: AcceptedTake time: 0msTake Memory: 228KBSubmit time: 2017-07-14 22:02:25****************************************************/