forked from likecs/Codechef-June-18-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsheokand_string.cpp
91 lines (83 loc) · 1.88 KB
/
sheokand_string.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
83
84
85
86
87
88
89
90
91
#include <bits/stdc++.h>
using namespace std;
const int LIM = 26;
struct node {
vector<int> ids;
node *child[LIM];
int leaf_id;
bool is_leaf;
};
char s[20];
node *trie;
node *get_node() {
node *temp = new node;
temp->ids.clear();
temp->leaf_id = 1000000;
temp->is_leaf = false;
for(int i = 0; i < LIM; ++i) {
temp->child[i] = NULL;
}
return temp;
}
void insert(node *root, int &id) {
int L = strlen(s);
for(int i = 0; i < L; ++i) {
if (root->child[s[i] - 'a'] == NULL) {
root->child[s[i] - 'a'] = get_node();
}
root = root->child[s[i] - 'a'];
root->ids.push_back(id);
}
root->leaf_id = min(root->leaf_id, id);
root->is_leaf = true;
}
void traverse_down(node *root, int r) {
while(root != NULL && (root->is_leaf == false ||
(root->is_leaf == true && root->leaf_id > r))) {
// bool done = false;
for(int i = 0; i < LIM; ++i) {
if (root->child[i] != NULL && root->child[i]->ids[0] <= r) {
// lowest character in range found.
root = root->child[i];
putchar(char(i + 'a'));
// done = true;
break;
}
// retry again till a complete word is found.
}
// assert(done);
}
}
void query(node *root, int r) {
int L = strlen(s);
for(int i = 0; i < L; ++i) {
if (root->child[s[i] - 'a'] != NULL) {
if (root->child[s[i] - 'a']->ids[0] <= r) {
// match found.
root = root->child[s[i] - 'a'];
putchar(s[i]);
continue;
}
}
// match not found.
break;
}
// either match is not found or complete word is still not printed.
traverse_down(root, r);
putchar('\n');
}
int main() {
int n, q, r;
scanf("%d", &n);
trie = get_node();
for(int i = 1; i <= n; ++i) {
scanf("%s", s);
insert(trie, i);
}
scanf("%d", &q);
for(int i = 1; i <= q; ++i) {
scanf("%d %s", &r, s);
query(trie, r);
}
return 0;
}