您的位置:首页 > 其它

HDU 1075 字典树 树搜索 逆路径输出单词

2016-08-05 13:09 369 查看
题目链接

题意: 给出一个字典 和 文章 根据字典翻译文章 字典中没有的词不用翻译 标点不用翻译

将字典中的所有单词都Insert进一颗字典树中 MAR单词的节点的Eng指针指向它对应的ENGLISH单词节点 所有Eng指针为NULL的不是MAR单词

找到对应的ENGLISH单词节点之后 又pre指针向上直到root 沿途将字母存入temp数组中最后将数组逆序

代码:

#include <cstdio>
#include <cstring>
#define sf scanf
#define pf printf
using namespace std;
const int sigm_size = 26;
typedef struct TrieNode* point;
struct TrieNode{
char value;
point Eng_point;
point next[26];
point pre;
}root;

point make_new_node(char value,point pre){
point cur = new TrieNode;
cur -> Eng_point = NULL;
for(int i = 0;i < 26;++i){
cur -> next[i] = NULL;
}
cur -> pre = pre;
cur -> value = value;
return cur;
}

void Insert_Mar(char *s,point value){
point cur = & root;
while(*s){
int idx = *s - 'a';
if(cur -> next[idx] == NULL){
cur -> next[idx] = make_new_node(*s,cur);
}
cur = cur -> next[idx];
s++;
}
cur -> Eng_point = value;
return;
}

point Insert_Eng(char* s){
point cur = & root;
while(*s){
int idx = *s - 'a';
if(cur -> next[idx] == NULL){
cur -> next[idx] = make_new_node(*s,cur);
}
cur = cur -> next[idx];
s++;
}
return cur;
}

void Insert_Pair(char* Eng,char* Mar){
Insert_Mar(Mar,Insert_Eng(Eng));
}

point Search_Mar(char* s,int len){          // 返回对应的ENG的指针 没有返回NULL则树中没有对应的MAR
point cur = &root;
for(int i = 0;i < len;++i){
int idx = s[i] - 'a';
if(cur -> next[idx] == NULL) return NULL;
cur = cur -> next[idx];
}
return cur -> Eng_point;
}

void Mar_To_Eng(char* s,int len,char* temp){
point End_Eng = Search_Mar(s,len);
if(End_Eng == NULL){
for(int i = 0;i < len;++i){
temp[i] = s[i];
}
temp[len] = '\0';
return;
}
int p = 0;
while(End_Eng != &root){
temp[p++] = End_Eng -> value;
End_Eng = End_Eng -> pre;
}
temp[p] = '\0';
strrev(temp);
return;
}

char buff[3005];
char Eng[15],Mar[15],temp[15];
int main(){
root.Eng_point = NULL;
root.pre = NULL;
root.value = '\0';
for(int i = 0;i < 26;++i) root.next[i] = NULL;

while( gets(buff) != 0){
if(buff[0] == 'S'){
continue;
}
else if(buff[0] == 'E'){
break;
}
else{
sscanf(buff,"%s %s",Eng,Mar);
Insert_Pair(Eng,Mar);
}
}

while(gets(buff) != 0){
if(buff[0] == 'S'){
continue;
}
else if(buff[0] == 'E'){
break;
}
else{
int buff_len = strlen(buff);
int pre = -1;
for(int i = 0;i < buff_len;++i){
if(buff[i] >= 'a' && buff[i] <= 'z'){
if(pre == -1) pre = i;
}
else {
if(pre != -1){
Mar_To_Eng(buff + pre,i - pre,temp);
pf("%s",temp);
}
pf("%c",buff[i]);
pre = -1;
}
}
if(pre != -1){
Mar_To_Eng(buff + pre,buff_len - pre,temp);
pf("%s",temp);
}
pf("\n");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  搜索