HDU 1075(简单字典树)

来源:互联网 发布:免税店mac多少钱 编辑:程序博客网 时间:2024/05/16 17:21

题意:第一个START,END中给出字典对照,第二个START,END 给出要翻译的句子。

 

#include <cstdio>#include <cstring>#include <iostream>using namespace std;char dictionary[1000000][11];struct Trie{    int sub;    Trie* next[26];    Trie() : sub(-1)    {        memset(next, 0, sizeof (next));    }};void insert(Trie* root, char* s, int pos){    Trie* p = root;    int i = 0, n;    while (s[i])    {        n = s[i++] - 'a';        if (p->next[n] == NULL)            p->next[n] = new Trie;        p = p->next[n];    }    p->sub = pos;}int search(Trie* root, char* s){    Trie* p = root;    int i = 0, n;    while (s[i])    {        n = s[i++] - 'a';        if (p->next[n] == NULL)            return -1;        p = p->next[n];    }    return p->sub;}int main(){    Trie* root = new Trie;    char line[3010], temp[11];    int pos = 0, i;    scanf("%s", line);    while (scanf("%s", line), strcmp(line, "END"))    {        strcpy(dictionary[pos], line);        scanf("%s", line);        insert(root, line, pos++);    }    scanf("%s", line);    getchar();    while (gets(line), strcmp(line, "END"))    {        i = 0;        while (line[i])        {            if (!(line[i] >= 'a' && line[i] <= 'z'))                putchar(line[i++]);            else            {                int start = i;                while (line[i] >= 'a' && line[i] <= 'z') ++i;                strncpy(temp, &line[start], i - start);                temp[i - start] = '\0';                printf("%s", (start = search(root, temp)) == -1 ? temp : dictionary[start]);            }        }        putchar('\n');    }    return 0;}


 

0 0
原创粉丝点击