题意:给你每个单词对应的意思,再输入一个单词,说出他的意思,如果单词不存在输出eh
思路:hash表保存单词,用另一个单词当做键值,实现快速查找
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
struct str
{
char s[12];
char s_str[12];
}Node;
vector<str> v[100003];
const int Mod = 100003;
int key(char *s)
{
int seed = 31,sum = 0;
int len = strlen(s);
for(int i = 0; i < len; i++)
{
sum = (sum*seed + s[i]) % Mod;
}
return sum;
}
void insert(char *s,char *ss)
{
int k = key(ss);
str temp;
strcpy(temp.s,s);
strcpy(temp.s_str,ss);
v[k].push_back(temp);
}
char * find(char *s)
{
int k = key(s);
for(int i = 0; i < v[k].size(); i++)
{
if(strcmp(s,v[k][i].s_str) == 0)
return v[k][i].s;
}
return NULL;
}
int main()
{
int i = 0;
char s[15],ss[15],c;
while((c = getchar()) != '\n')
{
if(c == ' ')
{
s[i] = '\0';
gets(ss);
insert(s,ss);
i = 0;
}
else
{
s[i++] = c;
}
}
while(scanf("%s",s) != EOF)
{
char *p = find(s);
if(p == NULL)
printf("eh\n");
else
printf("%s\n",p);
}
return 0;
}
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
struct Node
{
char str[15];
bool end;
Node *next[26];
};
Node * head;
Node* bulid()
{
Node * h= new Node;
memset(h->next,NULL,sizeof(h->next));
h -> end = false;
return h;
}
void insert(char *s,char *ss)
{
int len = strlen(ss);
Node * p = head,*q;
for(int i = 0; i < len; i++)
{
if(p -> next[ss[i]-'a'] != NULL)
{
p = p -> next[ss[i]-'a'];
}
else
{
q = new Node;
q -> end = false;
memset(q-> next,NULL,sizeof(q -> next));
p -> next[ss[i]-'a'] = q;
p = p -> next[ss[i]-'a'];
}
}
strcpy(p -> str,s); p -> end = true;
}
char* find(char *s)
{
int len = strlen(s);
Node * p = head;
for(int i = 0; i < len; i++)
{
if(p -> next[s[i]-'a'] != NULL)
{
p = p -> next[s[i]-'a'];
}
else
{
return NULL;
}
}
if(p -> end)
return p -> str;
else
return NULL;
}
int main()
{
int i = 0;
char s[15],ss[15],c;
head = bulid();
while((c = getchar()) != '\n')
{
if(c == ' ')
{
s[i] = '\0';
gets(ss);
insert(s,ss);
i = 0;
}
else
{
s[i++] = c;
}
}
while(scanf("%s",s) != EOF)
{
char *p = find(s);
if(p == NULL)
printf("eh\n");
else
printf("%s\n",p);
}
return 0;
}
串有可能出现前缀比如 字典树中保存abcd,我们查找abc,里面有但是他是abcd的前缀,所以不是单词,所以我们要做标记,标记的方法就是在结构体中加一个标记,标记他是否是单词的结尾,如果是则找到,如果不是则没找到