/*
* author : qiu
* coding : utf-8
* time : 2014-12--
* fun : Trie 树
*
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <iterator>
#include <sstream>
#include <fstream>
#include <queue>
#include <iomanip>
#define debug puts("-----")
#define pi (acos(-1.0))
#define eps (1e-8)
#define inf (1<<28)
using namespace std;
typedef struct node{
int val;
struct node *next[26];
}trie;
trie *build(){
trie *root=(trie*)malloc(sizeof(node));
root->val=1;
for(int i=0; i<26; i++)
root->next[i]=NULL;
return root;
}
void insert_tree(trie *root, char *s){
int i=0;
while(s[i] != 0){
int k=s[i]-'a';
if(!root->next[k])
root->next[k]=build();
else
root->next[k]->val++;
root=root->next[k];
i++;
}
}
int search_tree(trie *root, char *s){
int cnt=0, i=0;
while(s[i] !=0){
int k=s[i]-'a';
if(!root->next[k])
return 0;
cnt=root->next[k]->val;
root=root->next[k];
i++;
}
return cnt;
}
void Delete(trie *T){
if(T==NULL)
return;
for(int i=0; i<26; i++)
if(T->next[i]!=NULL)
Delete(T->next[i]);
free(T);
return ;
}
int main(){
trie *Root=build();
char s[15];
while(gets(s)&&strlen(s)){
insert_tree(Root, s);
}
while(~scanf("%s", s)){
printf("%d\n", search_tree(Root, s));
Delete(Root);
}
return 0;
}
字典树Trie 模板
最新推荐文章于 2023-10-05 18:14:23 发布