#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<cstdlib>
#define MAXNUM 26
using namespace std;
typedef struct Trie
{
bool flag;//标记从根到此是否为一个单词
char *s;
Trie *next[MAXNUM];
}Trie;
Trie *root;
void init()
{
root = (Trie *)malloc(sizeof(Trie));
root->flag=false;
for(int i=0;i<MAXNUM;i++)
root->next[i]=NULL;
}
void insertt(char *word,char *fword)
{
Trie *tem = root;
int u=0;
while(word[u]!='\0')
{
if(tem->next[word[u]-'a']==NULL)
{
Trie *cur = (Trie *)malloc(sizeof(Trie));
for(int i=0;i<MAXNUM;i++)
cur->next[i]=NULL;
cur->flag=false;
tem->next[word[u]-'a']=cur;
}
tem = tem->next[word[u]-'a'];
u++;
}
tem->s=(char *)malloc(sizeof(char));
strcpy(tem->s,fword);
//tem->s=strdup(fword);
tem->flag=true;
}
char * searcht(char *word)
{
Trie *tem = root;char *l="#";
for(int i=0;word[i]!='\0';i++)
{
if(tem==NULL||tem->next[word[i]-'a']==NULL)
return l;
tem=tem->next[word[i]-'a'];
}
if(tem->flag) //是单词则返回
return tem->s;
return l;
}
void del(Trie *cur)
{
for(int i=0;i<MAXNUM;i++)
{
if(cur->next[i]!=NULL)
del(cur->next[i]);
}
free(cur);
}
int main()
{
//freopen("1.in","r",stdin);
init();
char ch1[20],ch2[20];
scanf("%s",&ch1);
while(1)
{
scanf("%s",&ch1);
if(ch1[0]=='E'){break;}
scanf("%s",&ch2);
insertt(ch2,ch1);
}
scanf("%s",&ch1);
getchar();
while(1)
{
char ch[4010];
fgets(ch,4010,stdin);
if(ch[0]=='E')break;
int len=strlen(ch);
int i=0,j=0;
while(i<len)
{
while(i<len&&!isalpha(ch[i])){printf("%c",ch[i]);i++;}
j=i;
while(j<len&&isalpha(ch[j]))j++;
int k=0,c;
char x[3010];
if(i<j)
{
for(c=i;c<j;c++)x[k++]=ch[c];x[k]='\0';
char *y=searcht(x);
if(y[0]!='#')
{
printf("%s",y);
}
else
{
for(c=i;c<j;c++)printf("%c",ch[c]);
}
}
i=j;
}
}
del(root);
return 0;
}
hdu1075 字典树
最新推荐文章于 2019-01-10 21:49:00 发布