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

《数据结构学习与实验指导》5-2:字符串关键字的散列映射

2017-07-23 11:32 651 查看
实验内容:给定一系列由大写英文字母组成的字符串关键字和素数P,用移位法定义的散列函数H(Key)将关键字Key中的最后3个字符映射为整数,每个字符占5位;再用除留余数法将整数映射到长度为P的散列表中。例如将字符串“AZDEG”插入长度为1009的散列表中,首先将26个大写英文字母顺序映射到整数0~25;再通过移位将其映射为3×322+4×32+6=3206;然后根据表长得到3206%1009=179,即是该字符串的散列映射位置。发生冲突时请用平方探测法解决。

输入格式:

输入第一行首先给出两个正整数N(N≤500)和P(≥2N的最小素数),分别为待插入的关键字总数以及散列表的长度。第二行给出N个字符串关键字,每个长度不超过8位,其间以空格分隔。

输出格式:

在一行内输出每个字符串关键字在散列表中的位置。数字间以空格分隔,但行末尾不得有多余空格。

测试用例:

输入输出
4 11
HELLO ANNK ZOE LOLI
3 10 4 0
6 11
LLO ANNA NNK ZOJ INNK AAA
3 0 10 9 6 1
5 11
HELLO ANNA NNK ZOJ NNK
3 0 10 9 10
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MaxString 8

typedef struct Node {
char value[MaxString + 1];
int choosed;
} *PNode;

typedef struct HashTable {
PNode arr;
int size;
} *PHashTable;

int N, P;
int first = 1;

int char2int(char c);
int str2key(char cc[]);
int hash(char cc[]);
PHashTable init();
int insert(PHashTable table, char cc[]);

int main() {
scanf("%d %d", &N, &P);
PHashTable table = init();
char str[MaxString + 1];
int i;
for (i = 0; i < N; i++) {
scanf("%s", str);
int index = insert(table, str);
if (first) {
printf("%d", index);
first = 0;
} else {
printf(" %d", index);
}
}
return 0;
}

PHashTable init() {
PHashTable table = (PHashTable) malloc(sizeof(struct HashTable));
table->size = P;
table->arr = (PNode) malloc(sizeof(struct Node) * P);
int i;
for (i = 0; i < P; i++) {
table->arr[i].choosed = 0;
}
return table;
}

int insert(PHashTable table, char cc[]) {
int index = hash(cc);
int i = index;
int count = 1;
while (table->arr[i].choosed && strcmp(cc, table->arr[i].value) != 0) {
if (count % 2 != 0) {
i = (count + 1) / 2;
i = i * i;
} else {
i = count / 2;
i = -i * i;
}
i = i + index + table->size;
i %= table->size;
count++;
}
if (! table->arr[i].choosed) {
table->arr[i].choosed = 1;
strcpy(table->arr[i].value, cc);
}
return i;
}

int char2int(char c) {
return c - 'A';
}

int str2key(char cc[]) {
int len = strlen(cc);
int i = len - 1;
int key = char2int(cc[i]);
i--;
if (i >= 0) {
key += char2int(cc[i]) << 5;
}
i--;
if (i >= 0) {
key += char2int(cc[i]) << 10;
}
return key;
}

int hash(char cc[]) {
int key = str2key(cc);
return key % P;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构