给出字符串以及对应的值,并根据字符串进行查询。 部分代码已经给出,请补充完整,提交时请勿包含已经给出的代码。 GCC int main() { int sm[18000]; int n, m, a; char str[5]; scanf("%d%d", &n, &m); while (n--) { scanf("%s%d", &str, &a); sm[Hash(str)] = a; } while(m--) { scanf("%s", &str); printf("%d\n", sm[Hash(str)]); } return 0; }
时间: 2024-01-23 09:03:08 浏览: 26
这段代码使用了一个 `Hash` 函数来将字符串映射到哈希表中的索引。在这个代码中,`Hash` 函数没有给出,我们需要自己实现一个。
以下是一个简单的 `Hash` 函数示例,使用字符串的 ASCII 码值进行哈希:
```c
int Hash(char *str)
{
int hash = 0;
for (int i = 0; str[i] != '\0'; i++)
{
hash = (hash * 31 + str[i]) % 18000;
}
return hash;
}
```
在这个 `Hash` 函数中,我们使用了字符串的 ASCII 码值来计算哈希值。具体来说,我们将哈希值初始化为0,然后对于字符串中的每个字符,我们将当前哈希值乘以31,并加上该字符的 ASCII 码值,最后对18000取模得到哈希值。这个哈希函数的目的是将字符串转换成一个在0到17999之间的整数,以便于存储在 `sm` 数组中。
在补充完整代码后,我们可以使用类似下面的输入数据进行测试:
```
4 3
apple 3
banana 2
orange 5
grape 1
apple
orange
watermelon
```
其中,第一行的 `4 3` 表示有4个字符串及其对应的值,要查询3个字符串的值。接下来的4行分别是字符串及其对应的值,最后的3行是要查询的字符串。我们可以得到下面的完整代码:
```c
#include <stdio.h>
int Hash(char *str)
{
int hash = 0;
for (int i = 0; str[i] != '\0'; i++)
{
hash = (hash * 31 + str[i]) % 18000;
}
return hash;
}
int main()
{
int sm[18000];
int n, m, a;
char str[5];
scanf("%d%d", &n, &m);
while (n--)
{
scanf("%s%d", &str, &a);
sm[Hash(str)] = a;
}
while(m--)
{
scanf("%s", &str);
printf("%d\n", sm[Hash(str)]);
}
return 0;
}
```
输出结果为:
```
3
5
0
```
其中,`apple` 对应的值为3,`orange` 对应的值为5,`watermelon` 不在哈希表中,对应值为0。