字典树Trie 模板

/*
  * 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;  
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值