Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f7ee6f1

Browse files
Update trie code
1 parent ab6fee3 commit f7ee6f1

File tree

1 file changed

+37
-38
lines changed

1 file changed

+37
-38
lines changed

‎trie.cpp

Lines changed: 37 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -2,55 +2,54 @@
22
#define ll long long
33
using namespace std;
44

5-
struct trie_node {
6-
ll word_count;
7-
ll prefix_count;
8-
trie_node* edges[26];
9-
10-
trie_node() {
11-
this->word_count = 0;
12-
this->prefix_count = 0;
13-
for(int i = 0; i < 26; i++) {
14-
this->edges[i] = NULL;
15-
}
16-
}
5+
const int MAXN = 260005;
6+
7+
struct arr {
8+
int a[26];
9+
arr() {}
10+
void clear() { memset(a,-1,sizeof(a)); }
11+
int& operator[](int i) { return a[i]; }
1712
};
1813

19-
void add_word(trie_node* &root, string &str, int index) {
20-
if (index == str.length()) {
21-
root->word_count += 1;
22-
return;
23-
}
24-
root->prefix_count += 1;
25-
int i = int(str[index] - 'a');
26-
if (root->edges[i] == NULL) {
27-
root->edges[i] = new trie_node();
28-
}
29-
add_word(root->edges[i], str, index+1);
30-
}
14+
struct trie {
15+
int cnt, prefix_cnt[MAXN], word_cnt[MAXN];
16+
arr to[MAXN];
3117

32-
ll count_prefix(trie_node* root, string &prefix, int index) {
33-
if (index == prefix.length()) {
34-
return root->prefix_count;
18+
trie() { cnt = MAXN-1; }
19+
20+
void clear() { for(int i = 0; i < cnt; i++) prefix_cnt[i] = word_cnt[i] = 0, to[i].clear(); cnt = 1; }
21+
22+
void add(const string& s) {
23+
int u = 0;
24+
for(const char& c: s) {
25+
if(to[u][c-'a'] == -1) to[u][c-'a'] = cnt++;
26+
u = to[u][c-'a'];
27+
prefix_cnt[u]++;
28+
}
29+
word_cnt[u]++;
3530
}
36-
int i = int(prefix[index] - 'a');
37-
if (root->edges[i] == NULL) {
38-
return 0;
31+
32+
int prefix_count(const string& s) {
33+
int u = 0;
34+
for (const char& c: s) {
35+
if (to[u][c-'a'] == -1) return 0;
36+
u = to[u][c-'a'];
37+
}
38+
return prefix_cnt[u];
3939
}
40-
return count_prefix(root->edges[i], prefix, index+1);
41-
}
40+
} tr;
4241

4342
int main() {
44-
trie_node* root = newtrie_node();
43+
tr.clear();
4544
string s = "codechef";
46-
add_word(root, s, 0);
45+
tr.add(s);
4746
s = "codeforces";
48-
add_word(root, s, 0);
47+
tr.add(s);
4948
s = "youtube";
50-
add_word(root, s, 0);
49+
tr.add(s);
5150
s = "google";
52-
add_word(root, s, 0);
51+
tr.add(s);
5352
s = "code";
54-
cout<<count_prefix(root, s, 0)<<endl;
53+
cout<<tr.prefix_count(s)<<endl;
5554
return 0;
5655
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /