trie树

输入一系列字符串构成trie树 T ,空行,再输入字符串,查询 T 中以这些字符串为前缀的字符串数量。通过修改插入时,对 count 的操作,可以实现很多变形功能。杭电1251,1671

#include<iostream>
#include<vector>
#include<queue>
#include<string>
using namespace std;

#define TRIEMAX 26            //trie树中元素字符集大小,例如26个小写字母
struct trieNode{            //trie树节点
    int count;
    trieNode* childs[TRIEMAX];
    trieNode(){
        count = 0;
        for (int i = 0; i < TRIEMAX; ++i)
            childs[i] = NULL;
    }
};
/* 插入操作,主要变形可以通过对count的操作实现 */
void insertTrie(trieNode* root, string s)
{
    int k;
    trieNode *cur = root;
    for (int i = 0; i < s.size(); ++i){
        k = s[i] - 'a';
        if (cur->childs[k] != NULL){
            cur = cur->childs[k];
            ++(cur->count);
        }
        else{
            cur->childs[k] = new trieNode;
            ++(cur->childs[k]->count);
            cur = cur->childs[k];
        }
    }
}
/* 在trie树中查找 s */
int searchTrie(trieNode* root, string s){
    int k;
    trieNode *cur = root;
    for (int i = 0; i < s.size(); ++i){
        k = s[i] - 'a';
        if (cur->childs[k] == NULL) return 0;
        cur = cur->childs[k];
    }
    return cur->count;
}
/* 释放 trie 树 */
void freeTrie(trieNode* root)
{
    for (int i = 0; i < TRIEMAX; ++i)
        if (root->childs[i]) freeTrie(root->childs[i]);
    free(root);
}
/* 显示 trie树 */
void showTrie(trieNode* root){
    trieNode* p = NULL;
    queue<trieNode*> q;
    q.push(root);
    while (!q.empty()){
        p = q.front(); q.pop();
        if (p){
            cout << p->count << ' ';
            for (int i = 0; i < TRIEMAX; ++i)
                q.push(p->childs[i]);
        }
    }
    cout << endl;
}
/*
测试数据
banana
band
bee
absolute
acm

ba
b
band
abc
*/
int main()
{
    trieNode* root = new trieNode;
    string s;
    while (getline(cin, s)){
        if (!s.empty()){
            insertTrie(root, s);
        }
        else{
            showTrie(root);
            while (getline(cin, s)){
                if (s.empty()) return 0;
                cout << searchTrie(root, s) << endl;
            }
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/jokoz/p/4768376.html