forked from deutranium/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtries.cpp
82 lines (76 loc) · 1.54 KB
/
tries.cpp
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
// https://www.hackerearth.com/practice/data-structures/advanced-data-structures/trie-keyword-tree/tutorial/
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
struct trieNode
{
trieNode *sons[26];
int wt = 0;
trieNode()
{
for (int i = 0; i < 25; i++)
sons[i] = NULL;
wt = 0;
}
};
void insert(trieNode *root, string s, int w)
{
// cout<<"in insert"<<endl;
trieNode *node = root;
int n = s.size();
for (int i = 0; i < n; i++)
{
if (node->sons[s[i] - 'a'] == NULL)
{
trieNode *newNode = new trieNode;
newNode->wt = max(newNode->wt, w);
node->sons[s[i] - 'a'] = newNode;
}
node = node->sons[s[i] - 'a'];
node->wt = max(node->wt, w);
}
return;
}
int search(trieNode *node, string s)
{
int ans = -1;
int n = s.size();
for (int i = 0; i < n; i++)
{
if (node->sons[s[i] - 'a'] == NULL)
return -1;
node = node->sons[s[i] - 'a'];
ans = node->wt;
}
return ans;
}
void solve()
{
int n, q;
cin >> n >> q;
string s;
int wt;
trieNode *root = new trieNode;
while (n--)
{
cin >> s >> wt;
insert(root, s, wt);
}
// cout<<"done inserting"<<endl;
while (q--)
{
cin >> s;
cout << search(root, s) << endl;
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t = 1;
// cin >> t;
while (t--)
solve();
return 0;
}