题意:到了一个国家,这个国家的每个单词的意思跟英语单词的意思一一对应,让你输入英语单词查找是否有所要找的单词
思路:利用哈系函数,或是STL中的map
#include<iostream>
#include<cstdio>
#include<cstring>
#define MAXN 100003
using namespace std;
typedef char Word[12];
Word english[MAXN], foreign[MAXN];
const int HashSize = 100003;
int N, head[HashSize], next[HashSize];
void init_lookup_table() {
memset(head, 0, sizeof(head));
}
int hash(char *str) { // 字符串哈希函数
int hash = 0;
while (*str)
hash = hash * 10 + (*str++);
return
(hash & 0x7FFFFFFF) % HashSize;
}
int add_hash(int s) {
int h = hash(foreign[s]);
next[s] = head[h];
head[h] = s;
return 1;
}
int search(char *s) {
int h = hash(s);
int u = head[h];
while (u){
if(strcmp(foreign[u], s) == 0)
return u;
u = next[u];
}
return -1;
}
int main(){
char str[25];
N = 1;
init_lookup_table();
while (gets(str)){
if(str[0]=='\0')
break;
int i;
for(i = 0; str[i] != ' '; ++i)
english[N][i] = str[i];
english[N][i] = '\0';
char *p = str + i + 1;
i = 0;
while (*p)
foreign[N][i++] = *p++;
foreign[N][i] = '\0';
add_hash(N);
++N;
}
// 查询
while (gets(str)) {
int index = search(str);
if (index == -1)
puts("eh");
else
printf("%s\n", english[index]);
}
return 0;
}
STL
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<string>
#include<map>
using namespace std;
char str[100];
char a[30], b[30], c[30];
int main () {
map<string, string> s;
while (gets(str) != NULL) {
if (str[0] == '\0')
break;
sscanf(str, "%s%s", a, b);
s[b] = a;
}
while (gets(c)) {
if (s.find(c) == s.end())
printf("eh\n");
else
cout << s[c] << endl;
}
return 0;
}