Tire树

来源:互联网 发布:mac dashboard是什么 编辑:程序博客网 时间:2024/05/22 13:35

百度百科定义:

又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。

基本性质:

  1. 根节点不包含字符,根节点以外的节点都包含字符。
  2. 从根到该节点过程中所经过的字符串为词典中字符串的唯一前缀。
  3. 插入查找的复杂度位O(n), n为字符串长度。

原题地址:

http://hihocoder.com/problemset/problem/1014

定义节点的数据结构如下:

typedef struct Node{    int count;    struct Node *next[26];    bool judge;//是否能作为单词结尾 }Node; //节点数据结构 



因为每个字符串前缀在trie树中都处在唯一的路径下,在节点的数据结构里设置一个count变量,每当一个字符串词语录入到词典中,从根节点开始按字符串顺序向下查找,到单词到完整时在Node处设置judge为1说明可以生成一个单词;在词语录入过程中,每经过一个节点就在count上+1说明有更多一个词语以根节点到当前节点的字符串为前缀,这个count值也是我们最后需要输出的答案值。

源代码如下:

#include<iostream>#include<cstdlib>#include<cstdio>#include<string>#include<memory.h>using namespace std;typedef struct Node{    int count;    struct Node *next[26];    bool judge;//是否能作为单词结尾 }Node; //节点数据结构 Node* creatNode()//创建新节点以及初始化 {    Node* node;    node = (Node*)malloc(sizeof(Node));    node->count = 0;    node->judge = false;    memset(node->next, 0, sizeof(node->next));    return node; } void tree_create(Node *&root, string a)//a为输入字符串 {    char beitai;    Node *node = root;    for(int i=0; i<a.length(); i++)    {        beitai = a[i] - 'a';        if(node->next[beitai]==NULL) //如果接下里的字符节点不存在         {            node->next[beitai] = creatNode();        }        node = node->next[beitai];        node->count++;    }     //cout<<"finish"<<endl;}int tree_search(Node *&root, string a)//搜索字符串是否在词典当中 {    Node *node = root;    char beitai;    int mark;     for(int i=0; i<a.length(); i++)    {        beitai = a[i] - 'a';        if(node->next[beitai]==NULL)        {            return 0;        }        node = node->next[beitai];    }     return node->count;}int main(){    int Ans = 0;    int num,num1;    string input, search;    Node *root = creatNode();//创建初始根节点     cin>>num;    while(num--)    {        cin>>input;        tree_create(root, input);    }    cin>>num1;    while(num1--)    {        cin>>search;        cout<<tree_search(root,search)<<endl;    }    return 0;}
原创粉丝点击