zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    「B/S端开发」如何将DevExtreme组件添加到React应用程序?
    完整UI组件库Kendo UI for Vue R3 2021
    DevExpress WPF界面控件
    DevExpress WinForm MVVM数据和属性绑定指南(Part 1)
    界面控件Telerik UI for WinForm初级教程
    ua-parser-js 实现获取浏览器信息和操作系统信息
    vue--axios 拦截器的简单介绍及使用场景
    css 插件
    去除List集合中的重复值(四种好用的方法)
    常州大学/企业微信/电费查询脚本
  • 原文地址:https://www.cnblogs.com/jokoz/p/4768376.html
Copyright © 2011-2022 走看看