题意
给定一个词典,对于每一个给定的字符串,求以这个字符串开头的所有单词的个数。
题解
构建Trie树,节点附加一个域cnt,表示以从根到该节点结尾的字符串开头的单词个数。
每次insert一个单词,它经过的每个节点,其cnt都要加1。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
using namespace std;
struct TrieNode{
int cnt;
TrieNode* next[26];
TrieNode(int c = 0):cnt(c){ memset(next, 0, sizeof(next)); }
};
void insert(TrieNode* root, string& s){
TrieNode* p = root;
for(int i = 0; i < s.length(); ++i){
int id = s[i] - 'a';
if(!p->next[id]) p->next[id] = new TrieNode(1);
else p->next[id]->cnt++;
p = p->next[id];
}
}
int query(TrieNode* root, string& s){
TrieNode* p = root;
for(int i = 0; i < s.length(); ++i){
int id = s[i] - 'a';
if(p->next[id] == NULL) return 0;
p = p->next[id];
}
return p->cnt;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
#endif // ONLINE_JUDGE
int n, m;
while(cin >> n){
TrieNode* root = new TrieNode();
string s;
for(int i = 0; i < n; ++i){
cin >> s;
insert(root, s);
}
cin >> m;
for(int i = 0; i < m; ++i){
cin >> s;
cout << query(root, s) << endl;
}
}
return 0;
}