HDU 1075 字典树

传送门:HDU 1075

题意

 单词翻译


题解

trie树构造, 这题没有具体数据量所以动态建树最好
翻译时, 最后补一位空格符, 遍历字符串的时候遇到非字母时查询, 查到替换;遇到字母用数组保存当前数组


AC code:

/*
* Author : adrui
* Language : C++
* Result : Accepted
* Love : yy
* Favorite : Dragon Balls

* Standing in the Hall of Fame
*/


#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#include<iostream>
using namespace std;

#define debug 0
#define LL long long
#define inf 0x7f7f7f7f
#define mod 10003
#define mid ((l + r) >> 1)
#define ls rt << 1, l, mid
#define rs rt << 1|1, mid + 1, r
#define M(a, b) memset(a, b, sizeof(a))

const int maxn = 3000 + 5;

int idx(char p) {
    return p - 'a';
}

struct trie {
    int v;
    char word[12];
    trie *next[26];
    trie() {
        v = 0;
        M(next, 0);
    }


    char* query(char *s) {
        int len = strlen(s);
        trie *rt = this;

        for (int i = 0; i < len; ++i) {
            int c = idx(s[i]);
            if (!rt->next[c]) {
                return s;
            }
            rt = rt->next[c];
        }
        if (!rt->v) return s;
        return rt->word;
    }

    void insert(char *s, char *tmp) {
        trie *rt = this;
        int len = strlen(s);
        for (int i = 0; i < len; ++i) {
            int c = idx(s[i]);
            if (!rt->next[c]) {
                rt->next[c] = new trie;
            }
            rt = rt->next[c];
        }
        rt->v = 1;
        strcpy(rt->word, tmp);
    }
};

int main() {
#if debug
    freopen("in.txt", "r", stdin);
#endif //debug

    cin.tie(0);
    cin.sync_with_stdio(false);


    int cnt = 0;
    char s[maxn], t[maxn], a[12], b[12], *p;

    trie root;

    cin >> a;
    while (cin >> a, strcmp(a, "END")) {
        cin >> b;
        root.insert(b, a);
        //cout << a << b << endl;
    }

    cin >> a;
    gets_s(a);
    while (gets_s(s), strcmp(s, "END")) {
        int len = strlen(s);
        s[len++] = ' ';
        s[len] = '\0';

        for (int i = 0; i < len; ++i) {
            if (!islower(s[i])) {
                t[cnt] = '\0';
                cnt = 0;
                p = root.query(t);
                cout << p;
                if (i == len - 1) continue;
                cout << s[i];
            }
            else t[cnt++] = s[i];
        }
        cout << endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值