依旧字典树,题目读入有点难搞~~
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
char ch[3001];
struct Trie
{
Trie *ch[26];
char *cc;
};
Trie *H;
Trie *newnode()
{
Trie *p = new Trie;
for(int i = 0; i < 26; i++)
{
p->ch[i] = NULL;
}
p->cc = NULL;
return p;
}
void init()
{
H = newnode();
}
int idx(char c)
{
return c - 'a';
}
void insert(char *ss, char *xx)
{
int len = strlen(ss);
Trie *p = H;
for(int i = 0; i < len; i++)
{
int c = idx(ss[i]);
if(p->ch[c] == NULL)
{
p->ch[c] = newnode();
//printf("newnode:i:%d\n", i);
}
p = p->ch[c];
}
//printf("insert:%s\n", xx);
p->cc = new char[20];
strcpy(p->cc, xx);
}
void query(char *ss)
{
int len = strlen(ss);
Trie *p = H;
for(int i = 0; i < len; i++)
{
int c = idx(ss[i]);
if(p->ch[c] != NULL)
{
p=p->ch[c];
}
else
{
printf("%s", ss);
return ;
}
}
if(p->cc != NULL)
printf("%s", p->cc);
else
printf("%s", ss);
}
int main()
{
init();
char c1[3000], c2[3000], c3[3001], temp;
scanf("%*s");
while(scanf("%s", c1),strcmp(c1, "END"))
{
scanf("%s", c2);
insert(c2, c1);
}
scanf("%*s");
getchar();
int cnt = 0;
while(1)
{
temp = getchar();
if(isalpha(temp))
{
c3[cnt++] = temp;
}
else
{
c3[cnt] = '\0';
if(strcmp(c3, "END") == 0)
{
break;
}
if(cnt)
query(c3);
cnt = 0;
putchar(temp);
}
}
return 0;
}