Trie模板题
不同的是在建树时同时统计出现次数
模板请看
https://github.com/yyecust/icpctemplate/blob/master/字符串.md#trie
#include <bits/stdc++.h>
using namespace std;
int nextInt()
{
int x;
scanf("%d\n", &x);
return x;
}
string nextLine()
{
string s;
getline(cin, s);
return s;
}
//Trie
const int R = 26;
struct Node
{
Node(int v) {
memset(ch, 0, sizeof(ch));
val = v;
}
int ch[R];
int val;
};
/*
void put(string, int) 将string插入Trie 附加信息为int
int get(string) 返回string的附加信息
void print() 打印Trie
*/
struct Trie {
vector<Node> tree;
Trie() {
Node root(0);
tree.push_back(root);
}
int idx(char ch) {
return ch - 'a';
}
void put(string s)
{
int u = 0, n = s.size();
for (int i = 0; i < n; i++) {
int c = idx(s[i]);
if (!tree[u].ch[c]) {
tree[u].ch[c] = tree.size();
tree.push_back(Node(0));
}
u = tree[u].ch[c];
tree[u].val++;
}
}
int get(string s) {
int u = 0;
for (int i = 0; i < s.size(); i++) {
int c = idx(s[i]);
if (!tree[u].ch[c]) return false;
u = tree[u].ch[c];
}
return tree[u].val;
}
void print() {
for (int i = 0; i < tree.size(); i++) {
for (int j = 0; j < R; j++) {
cout << tree[i].ch[j] << ' ';
}
cout << endl;
}
}
};
int main()
{
//freopen("in.txt", "r", stdin);
int n = nextInt();
Trie trie;
while (n--) {
string s = nextLine();
trie.put(s);
}
int m = nextInt();
while (m--) {
string s = nextLine();
cout << trie.get(s) << endl;
}
}