-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.cc
86 lines (79 loc) · 1.56 KB
/
trie.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <string>
#include <map>
#include <fstream>
using namespace std;
struct Node
{
int num;
map<char, Node *> *child;
Node(int n=0):num(n),child(new map<char, Node *>()) {}
};
void build(Node *root, string &s, int n)
{
if (n == s.size())
return;
map<char, Node *>::const_iterator it = root->child->find(s[n]);
if (it == root->child->end())
{
root->num++;
Node *tmp = new Node();
root->child->insert(pair<char, Node *>(s[n], tmp));
build(tmp, s, ++n);
}
else
{
root->num++;
build(it->second, s, ++n);
}
}
int search(Node *root, string &s)
{
Node *t = root;
int ret = 0;
map<char, Node *>::const_iterator it;
for (int i=0; i<s.size(); ++i)
{
it = t->child->find(s[i]);
if (it == t->child->end())
return 0;
else
{
t = it->second;
ret = t->num;
}
}
return t->num;
}
int main()
{
int n,m;
string s;
ifstream fin;
//streambuf *backup;
if (false)
{
fin.open("data.in");
//backup = cin.rdbuf();
cin.rdbuf(fin.rdbuf());
}
//cout<<"input n:";
cin>>n;
Node *root = new Node(0);
for (int i=0; i<n; ++i)
{
cin>>s;
build(root, s, 0);
}
//cout<<"input m: ";
//cout<<"root num:"<<root->num<<endl;
cin>>m;
for (int i=0; i<m; ++i)
{
cin>>s;
//cout<<"search "<<s<<" : ";
cout<<search(root, s)<<endl;
}
//cout<<"end"<<endl;
return 0;
}