题目链接:
http://hihocoder.com/problemset/problem/1014
题意:
给定n个单词,然后我们构成1个字典树,然后再给你m个串,求有多少个单词是以这个串为前缀的。
代码以下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 100010;
const int max_size = 30;
int id(char c){
return c-'a';
}
struct Trie{
Trie *ch[max_size];
int num;
Trie(){
num = 0;
for(int i=0;i<max_size;i++)
ch[i]=NULL;
}
}*root;
void insert_str(char *s){
Trie *p = root;
p->num++;
for(int i=0; p&&s[i] ; i++){
int u = id(s[i]);
if(p->ch[u]==NULL)
p->ch[u] = new Trie;
p=p->ch[u];
p->num++;
}
}
int find_str(char *s){
Trie *p = root;
for(int i=0;p&&s[i];i++){
int u = id(s[i]);
if(p->ch[u]==NULL) return 0;
p=p->ch[u];
}
return p->num;
}
int main()
{
char s[12];
int n, m;
while(~scanf("%d", &n))
{
root = new Trie;
while(n--){
scanf("%s", s);
insert_str(s);
}
scanf("%d", &m);
while(m--){
scanf("%s", s);
printf("%d
", find_str(s));
}
}
return 0;
}