Trie

 1 /**************************************************
 2           Target: Trie
 3           Author: Xue Zhonghao
 4           Date: 2014-3-17 19:50:56 
 5 **************************************************/ 
 6 #include<cstdio>
 7 #include<cstring>
 8 #include<iostream>
 9 using namespace std;
10 
11 #define maxnode 1000
12 
13 struct Tree{
14     int head[maxnode];
15     int next[maxnode];
16     char ch[maxnode];
17     int val[maxnode];
18     int sz;
19     Tree() { sz = 1; head[0] = next[0] = 0; }
20     
21     void insert(string& s, int value) {
22       int u = 0, v, n = s.length();
23       for(int i = 0; i < n; ++i) {
24         bool found = false;
25         for(v = head[u]; v != 0; v = next[v])
26           if(ch[v] == s[i]) {
27             found = true;
28             break;
29           }
30         if(!found) {
31           v = sz++;
32           val[v] = value;
33           ch[v] = s[i];
34           next[v] = head[u];
35           head[u] = v;
36           head[v] = 0;
37         }
38         u = v;
39         val[u] = value;
40       }
41     }
42     
43     int find(string& s) {
44       int u = 0, v, n = s.length();
45       for(int i = 0; i < n; ++i) {
46         bool found = false;
47         for(v = head[u]; v != 0; v = next[v])
48           if(ch[v] == s[i]) {
49             found = true;
50             break;
51           }
52         if(!found) return -1;
53         u = v;
54       }
55       return val[u];
56     }
57 };
58 
59 Tree tree;
60 
61 int main(void)
62 {
63     int N;
64     string st;
65     cin>>N;
66     for(int i = 0; i < N; ++i) {
67       cin>>st;
68       tree.insert(st, i);
69     }
70     cout<<"hehehe"<<endl;
71     while(cin>>st) cout<<tree.find(st)<<endl;
72     return 0;
73 }

 

posted on 2014-04-07 16:38  AlanXue  阅读(161)  评论(0)    收藏  举报

导航