POJ 2503 Trie

链接:

http://poj.org/problem?id=2503

题意:

给定一些字符串以及它在外星语言中的对应翻译,现在有若干外星语言中的串,要把它们翻译成英语

题解:

这道题map,hash,trie都是可以做的

然而我用g++提交发现map和trie都超时了,换成c++就全都过了

map用了1141ms,trie只要485ms

代码:

31 vector<string> word;
32 int pi =1;
33 
34 struct Node {
35     int next[26];
36     int value;
37     bool end;
38 }tree[MAXN * 10];
39 
40 void insert(string keyword, int value) {
41     int index, p, i;
42     for (i = p = 0; keyword[i]; i++) {
43         index = keyword[i] - 'a';
44         if (tree[p].next[index] == 0)
45             tree[p].next[index] = pi++;
46         p = tree[p].next[index];
47     }
48     tree[p].value = value;
49     tree[p].end = 1;
50 }
51 
52 int query(string keyword) {
53     int index, p, i;
54     for (i = p = 0; keyword[i]; i++) {
55         index = keyword[i] - 'a';
56         if (tree[p].next[index] == 0) return 0;
57         p = tree[p].next[index];
58     }
59     if (tree[p].end) return tree[p].value;
60     return 0;
61 }
62 
63 int main() {
64     string s, a, b;
65     word.pb("eh");
66     while (getline(cin, s) && s != "") {
67         int fg = 1;
68         rep(i, 0, s.length()) {
69             if (s[i] == ' ') fg = 0;
70             else if (fg) a += s[i];
71             else b += s[i];
72         }
73         word.pb(a);
74         insert(b, word.size() - 1);
75         a = b = "";
76     }
77     while (cin >> a) cout << word[query(a)] << endl;
78     return 0;
79 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值