码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 2503 Trie

时间:2017-04-24 23:19:53      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:href   logs   index   node   oid   else   str   end   max   

链接:

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 }

 

POJ 2503 Trie

标签:href   logs   index   node   oid   else   str   end   max   

原文地址:http://www.cnblogs.com/baocong/p/6758996.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!