POJ 2503 Babelfish(字典树水题)

来源:互联网 发布:php微信服务号开发教程 编辑:程序博客网 时间:2024/04/29 00:41

题意:

输入一个字典,字典格式为“英语 外语”的一一映射关系
然后输入若干个外语单词,输出他们的 英语翻译单词,如果字典中不存在这个单词,则输出“eh”

解析:

对于所有给定的单词建立一颗字典树,然后对于每次给出的单词用字典树进行查询。

my code

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;struct Node {    Node* child[26];    char word[15];    bool isWord;    Node() {        for(int i = 0; i < 26; i++)            child[i] = NULL;        isWord = false;    }};char noWord[] = "eh";inline int idx(char c) {    return c - 'a';}void insert(Node* node, char* key, char* value) {    while(*key) {        int id = idx(*key);        if(node->child[id] == NULL)            node->child[id] = new Node();           node = node->child[id];        key++;    }    node->isWord = true;    strcpy(node->word, value);}char* search(Node* node, char* key) {    while(*key) {        int id = idx(*key);        if(node->child[id] == NULL)            return noWord;        node = node->child[id];        key++;    }    if(node->isWord)        return node->word;    return noWord;}int main() {    char buf[40], key[20], value[20];    Node* root = new Node();    while(gets(buf) && buf[0] != '\0') {        sscanf(buf, "%s%s", value, key);        insert(root, key, value);    }    while(scanf("%s", key) != EOF) {        printf("%s\n", search(root, key));    }    return 0;}
0 0
原创粉丝点击