1 条题解
-
0
解题思路:
- 可以使用一个数据结构(如哈希表)来存储字典中的词条,键为外语单词,值为对应的英语单词。
- 读取输入的字典词条,将其存入哈希表中。
- 读取外语消息中的每个单词,在哈希表中查找对应的英语单词。若找到则输出该英语单词,若未找到则输出 “eh”。
实现步骤
- 定义一个合适的数据结构来存储字典词条。
- 读取字典词条,将每个词条的外语单词作为键,英语单词作为值存入数据结构中。
- 读取空行(可简单跳过)。
- 读取外语消息中的每个单词:在数据结构中查找该单词。如果找到,输出对应的值(英语单词)。如果未找到,输出 “eh”
代码
#include <stdio.h> #include <string.h> const int M = 200000; struct word { char e[11]; char f[11]; int next; }; word dict[M]; int n = 1; int Hash[M]; int ELFHash(char* key) { unsigned int h = 0; while(*key) { h = (h<<4) + (*key++); unsigned int g = h&(0xf00000000L); if(g) h^=g>>24; h&=~g; } return h%M; } void find(char f[]) { int h = ELFHash(f); for(int k=Hash[h]; k; k=dict[k].next) { if(strcmp(f, dict[k].f)==0) { printf("%s\n",dict[k].e); return ; } } printf("eh\n"); } int main() { char str[23]; while (fgets(str, sizeof(str), stdin) != NULL) { // 去除换行符 str[strcspn(str, "\n")] = 0; if (str[0] == '\0') break; sscanf(str, "%s %s", dict[n].e, dict[n].f); int h = ELFHash(dict[n].f); dict[n].next = Hash[h]; Hash[h] = n++; } while (fgets(str, sizeof(str), stdin) != NULL) { // 去除换行符 str[strcspn(str, "\n")] = 0; find(str); } return 0; }
- 1
信息
- ID
- 1504
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 10
- 标签
- 递交数
- 3
- 已通过
- 2
- 上传者