• Trie[字典树] 数据结构及基本操作集


    #include <iostream>
    #include <stdio.h>
    #include <cstring>
    #include <algorithm>
    #include <vector>
    using namespace std;
    #define Max 26
    typedef struct TrieNode *Trie;
    struct TrieNode
    {
        Trie next[Max];
        int num;
        TrieNode()
        {
            for (int i = 0; i < Max; i++)
                next[i] = NULL;
            num = 0;
        }
    };
    
    
    void Insert(Trie root,char *s)
    {
        Trie p = root;
        for (int i = 0; s[i]; i++) {
            int t = s[i]-'a';
            if (p->next[t] == NULL)
                p->next[t] = new TrieNode;
            p = p->next[t];
        }
        p->num++;
    }
    
    void Delete(Trie root, char *s)
    {
        int len = strlen(s);
        Trie p = root;
        for (int i = 0; i < len; i++) {
            int t = s[i]-'a';
            if (p->next[t] == NULL)
                return;
            p = p->next[t];
        }
        p->num--;
    }
    
    bool Search(Trie root, char *s)
    {
        Trie p = root;
        if (p == NULL)
            return 0;
        int len = strlen(s);
        for (int i = 0; i < len; i++) {
            int t = s[i]-'a';
            if (p->next[t] == NULL)
                return 0;
            p = p->next[t];
        }
        return p->num > 0;
    }
    
    void PrintDic(Trie root, vector<vector<char> > &words, vector<char> &word)
    {
        if (root == NULL)
            return;
        if (root->num > 0)
            words.push_back(word);
        for (int i = 0; i < Max; i++) {
            if (root->next[i]) {
                word.push_back('a'+i);
                PrintDic(root->next[i], words, word);
                word.pop_back();
            }
        }
    }
    
    void FreeTrie(Trie root)
    {
        for (int i = 0; i < Max; i++) {
            if (root->next[i] != NULL)
                FreeTrie(root->next[i]);
        }
        delete root;
    }
    
    int main()
    {
        freopen("1.txt", "r", stdin);
        Trie root = new TrieNode;
        char s[300];
        while (cin >> s) {
            Insert(root, s);
        }
        //char temp[50] = "avvvvefaf";
        //cout << Search(root, temp);
        //Delete(root, temp);
        //cout << Search(root, temp);
    
        vector<char> word;
        vector<vector<char> >words;
        PrintDic(root, words, word);
        for (int i = 0; i < words.size(); i++) {
            for (int j = 0; j < words[i].size(); j++) {
                printf("%c", words[i][j]);
            }
            printf("
    ");
        }
    
    
    
        return 0;
    }
  • 相关阅读:
    关系数据库元数据处理类(一) 创建元数据实体
    常用通用简单文件上传功能
    基于NOPI的Execl模板转换类,直接将Execl模板转换对应的Entity
    CSS彻底研究(3)
    CSS彻底研究(2)
    CSS彻底研究(1)
    CLR via C#
    前端JS模版库kino.razor
    CLR via C#
    CLR via C#
  • 原文地址:https://www.cnblogs.com/whileskies/p/7273528.html
Copyright © 2020-2023  润新知