题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1075
题目大意:
先给出一些单词的英文翻译,然后给出一篇文章,存在标点,若文章中单词存在翻译,则转换成英文单词,若没有则不变,然后输出翻译后的文章
分析:
建立一个译文数组,在字典树中插入单词时,即可在单词结点处添加对应译文在数组中的下标,然后遍历文章,遇到标点与空格切分单词,特判最后末尾不是标点的情况,在树中查找是否出现过当前单词即可,存在即将单词的译文输出,否则输出原文,然后将当前遍历的标点直接输出
代码:
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cmath>
#include<map>
using namespace std;
typedef long long ll;
struct Trie{
Trie *next[26];
int val;
Trie(){
val = -1;
for (int i = 0 ; i < 26 ; i ++)
next[i] = NULL;
}
};
void addword(char *str,Trie* node,int i)
{
if (node->next[str[0]-'a']==NULL)
{
node->next[str[0]-'a'] = new Trie;
node = node->next[str[0]-'a'];
}
else
{
node = node->next[str[0]-'a'];
}
str++;
if (*str)
addword(str,node,i);
else
{
node->val = i;
return;
}
}
int query(char *str ,Trie *node)
{
if (node->next[*str-'a']==NULL)
return -1;
else
node= node->next[*str-'a'];
++str;
if (*str)
return query(str,node);
else
return node->val;
}
char str[4000];
char temp[4000],tw[4000];
char word[1200000][20];
int main()
{
int T,n,i;
int cnt = 0;
Trie* head = new Trie;
scanf("%s",str);
getchar();
gets(str);
while (strcmp(str,"END")!=0)
{
for (i = 0 ; ; i ++)
{
if (str[i]==' ')
{
word[cnt][i++] = 0;
break;
}
else
word[cnt][i] = str[i];
}
cnt++;
addword(str+i,head,cnt-1);
gets(str);
}
scanf("%s",str);
getchar();
gets(str);
int lw;
while (strcmp(str,"END")!=0)
{
cnt =0;
int tp = 0;
memset(temp,0,sizeof(temp));
for (i = 0; str[i]; i ++)
{
if (str[i]>='a'&&str[i]<='z')
{
tw[cnt++] = str[i];
}
else
{
if (cnt!=0)
{
tw[cnt] = 0;
int pos = query(tw,head);
if (pos!=-1)
{
strcat(temp,word[pos]);
tp += strlen(word[pos]);
}
else
{
strcat(temp,tw);
tp += strlen(tw);
}
cnt = 0;
}
temp[tp++] = str[i];
}
}
if (cnt!=0)
{
tw[cnt] = 0;
int pos = query(tw,head);
if (pos!=-1)
{
strcat(temp,word[pos]);
tp += strlen(word[pos]);
}
else
{
strcat(temp,tw);
tp += strlen(tw);
}
cnt = 0;
}
temp[tp] = 0;
printf("%s\n",temp);
gets(str);
}
return 0;
}