在建树的时候记录每个火星单词对应的英语单词位置,在查找时候输出
相应的位置
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct Trie
{
int x;
Trie *next[26];
} root;
char ch[1000010][15], ch1[15], str[3002];
void createTrie(char *str, int y)
{
int len = strlen(str);
Trie *p = &root, *q;
for(int i = 0; i < len; i++)
{
int id = str[i] - 'a';
if(p->next[id] == NULL)
{
q = new Trie;
q->x = -1;
for(int j = 0; j < 26; j++) q->next[j] = NULL;
p->next[id] = q;
}
p = p->next[id];
}
p->x = y;
}
int findTrie(char *str, int len)
{
if(!len) return -1;//这里注意
Trie *p = &root;
for(int i = 0; i < len; i++)
{
int id = str[i] - 'a';
p = p->next[id];
if(p == NULL) return -1;
}
return p->x;
}
int main()
{
int k = 0;
scanf("%s%*c", ch1);
for(int i = 0; i < 26; i++) root.next[i] = NULL;
while(scanf("%s", ch[k]) && ch[k][0] != 'E')
{
scanf("%s", ch1);
createTrie(ch1, k++);
}
scanf("%s%*c", ch1);
while(gets(str) && str[0] != 'E')
{
int len = strlen(str);
int g = 0, i;
for(i = 0; i < len; i++)
{
if(str[i] >= 'a' && str[i] <= 'z') ch1[g++] = str[i];
else
{
ch1[g] = '\0';
int ans = findTrie(ch1, g);
g = 0;
if(ans == -1) printf("%s%c", ch1, str[i]);
else printf("%s%c", ch[ans], str[i]);
}
}
if(ch1[g-1] >= 'a' && ch1[g-1] <= 'z')
{
int ans = findTrie(ch1, g);
if(ans == -1) printf("%s%c", ch1, str[i]);
else printf("%s%c", ch[ans], str[i]);
}
printf("\n");
}
}
hdu 1075 字典树
最新推荐文章于 2019-01-10 21:49:00 发布