HDU 1075(简单字典树)

本文介绍了一个使用字典树(Trie)结构实现的简单翻译系统。该系统首先通过读取输入来构建字典树,然后利用构建好的字典树进行翻译任务。文章提供了完整的C++实现代码,包括插入单词到字典树、搜索单词及其对应的翻译等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:第一个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;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值