码迷,mamicode.com
首页 > 其他好文 > 详细

trie树

时间:2015-08-29 09:41:43      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

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

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

#define TRIEMAX 26
struct trieNode{
    int count;
    trieNode* childs[TRIEMAX];
    trieNode(){
        count = 0;
        for (int i = 0; i < TRIEMAX; ++i)
            childs[i] = NULL;
    }
};
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];
        }
    }
}
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;
}
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;
}

 

trie树

标签:

原文地址:http://www.cnblogs.com/jokoz/p/4768376.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!