-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtrie.cpp
More file actions
57 lines (51 loc) · 913 Bytes
/
trie.cpp
File metadata and controls
57 lines (51 loc) · 913 Bytes
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
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 1;
int n,q,cnt;
int tree[N][26],res[N];
void add(string s,int x)
{
int cur = 0;
for(char c : s)
{
if(tree[cur][c-'a']==0)
{
tree[cur][c-'a'] = ++cnt;
cur = cnt;
res[cur] = x;
}
else
{
cur = tree[cur][c-'a'];
res[cur] = max(res[cur],x);
}
}
}
int find(string s)
{
int cur = 0;
for(char c : s)
{
if(tree[cur][c-'a']==0) return -1;
cur = tree[cur][c-'a'];
}
return res[cur];
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> n >> q;
for(int i = 0;i < n;i++)
{
string s;
int x;
cin >> s >> x;
add(s,x);
}
for(int i = 0;i < q;i++)
{
string s;
cin >> s;
cout << find(s) << '\n';
}
}