HihoCoder - 1014 Trie树 (字典树入门)
题目:点击打开链接
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
char s[15];
typedef struct Node* node;
struct Node
{
int Num;//常见的是存数,具体的根据题更改
node Next[26];
Node()
{
Num = 0;
memset(Next,NULL,sizeof(Next));
}
};
void Insert(node root)
{
node p = root;
int len = strlen(s);
for(int i=0 ; i<len ; i++)
{
int mid = s[i] - 'a';
if(p->Next[mid] == NULL)p->Next[mid] = new struct Node();
p = p->Next[mid];
p->Num++;
}
}
int Judge(node root)
{
int len = strlen(s);
node p = root;
for(int i=0 ; i<len ; i++)
{
int mid = s[i] - 'a';
if(p->Next[mid])p = p->Next[mid];
else return 0;
}
return p->Num;
}
void Del(node root){
for(int i=0 ; i<26 ; ++i){
if(root->Next[i])Del(root->Next[i]);
}
delete(root);
}
int main(){
int N,M;
while(scanf("%d",&N)!=EOF){
node root = new struct Node();
for(int i=0 ; i<N ; ++i){
scanf("%s",s);
Insert(root);
}
scanf("%d",&M);
for(int i=0 ; i<M ; ++i){
scanf("%s",s);
printf("%d\n",Judge(root));
}
Del(root);
}
return 0;
}