版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/84898532
我的数据结构与算法题目集代码仓:https://github.com/617076674/Data-structure-and-algorithm-topic-set
原题链接:https://pintia.cn/problem-sets/15/problems/890
题目描述:
知识点:哈希表
思路:字符串哈希
和数据结构与算法题目集7-42——整型关键字的散列映射中的注意点一样,有可能该字符串已经在哈希表中,这时候我们不需要插入,只需输出其在哈希表中的位置即可。
C++代码:
#include<iostream>
#include<cstring>
using namespace std;
int changeToInt(char* str);
int main() {
int N, P;
scanf("%d %d", &N, &P);
char strs[P][9];
bool filled[P];
fill(filled, filled + P, false);
for(int i = 0; i < N; i++){
char input[9];
scanf("%s", input);
int num = changeToInt(input);
for(int j = 0; j < P; j++){
int index1 = (num + j * j) % P;
if(!filled[index1] || strcmp(strs[index1], input) == 0){
filled[index1] = true;
strcpy(strs[index1], input);
printf("%d", index1);
break;
}
int index2 = (num - j * j) % P;
while(index2 < 0){
index2 += P;
}
if(!filled[index2] || strcmp(strs[index2], input) == 0){
filled[index2] = true;
strcpy(strs[index2], input);
printf("%d", index2);
break;
}
}
if(i == N - 1){
printf("\n");
}else{
printf(" ");
}
}
return 0;
}
int changeToInt(char* str) {
int result = 0;
int len = strlen(str);
for(int i = max(len - 3, 0); i < len; i++) {
result = result * 32 + str[i] - 'A';
}
return result;
}
C++解题报告: