-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.cpp
executable file
·74 lines (67 loc) · 1.31 KB
/
trie.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
/*
*@author:cmershen
*@description:Trie树模板,求指定前缀的字符串在词典里有几个
*/
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include <stdio.h>
using namespace std;
#define INTMAX 2147483647
#define INTMIN -2147483648
const int max_sigma = 26;
class Node{
public:
Node* next[max_sigma];
int cnt;
Node(){
memset(next, 0, sizeof(next));
cnt = 0;
}
};
class Trie : public Node {
public:
Node *root;
void insert(char* s){
int c;
Node* p = root;
while(*s != NULL){
c = *s - 'a';
if(p->next[c] == NULL) {
p->next[c] = new Node();
}
p = p->next[c];
s++;
p->cnt++;
}
}
int find(char* s){
int c;
Node* p = root;
while(*s != NULL){
c = *s - 'a';
p = p->next[c];
if(p == NULL)
return 0;
s++;
}
return p->cnt;
}
}t;
char word[1000002]; //word开小了,会RE!!!
int main(){
int n,m;
t.root=new Node();
cin>>n;
while(n--) {
scanf("%s",word);
t.insert(word);
}
cin>>m;
while(m--) {
scanf("%s",word);
cout<<t.find(word)<<endl;
}
return 0;
}