c++ - Trie map 实现

标签 c++ dictionary data-structures trie

我今天正在解决一个问题。但是我被卡住了。我知道 trie 是如何工作的,但问题是我知道如何使用静态数组和类来实现它。今天在网上冲浪,我读到有一种方法可以使用 STL::map 来实现尝试。我今天试过了,但我仍然不知道如何在 int 上插入元素。 这种结构。

Edit1:我正在尝试解决这个问题:spoj.com/problems/TAP2012D 我想知道如何将单词添加到 trie 中 edit2:我知道 map 是如何工作的,我只是不知道带有 map 的特里树是如何工作的。我想要知道尝试的人。

这是我到目前为止所做的

const int ALPH_SIZE = 26;
using namespace std;

struct trie{
    map<char,int> M;
    int x,y;
    trie();
};

trie T[1000000];


trie::trie()
{
    x=y=0;
}
int maximo;


void addtrie(string palabra)
{
    int tam=palabra.size();
    int pos=0;
    for(int i=0;i<tam;i++)
    {
        if(T[pos].M.find(palabra[i])==T[pos].M.end())
        {
            T[pos].M[palabra[i]]=new trie();
            T[pos].M[palabra[i]]=
        }

    }

}

最佳答案

trie 节点存储现有字符的映射和指示该节点是否对应于 trie 中的单词的标志。

struct Node
{   map<char, Node*> a;
    bool flag;

    Node() { flag = false; }
};

现在插入类似于您对静态数组执行的操作,只是您在这里使用的是映射。

void insert(Node *x, string s)
{   for(int i = 0; i < s.size(); i++)
    {   if(x->a.count(s[i]) == 0)
        /* no outgoing edge with label = s[i] so make one */
        {   x->a[ s[i] ] = new Node;
        }
        x = x->a[ s[i] ];
    }
    x->flag = true; /* new word */
}

关于c++ - Trie map 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14887433/

相关文章:

c++ - 共享指针上的原子操作,C++ 版本

c++ - 使用 IDE 构建 Emscripten 项目?

c++ - 如何对动态数组执行操作?

algorithm - 寻找最可靠的路径——Dijkstra算法

algorithm - 构建二叉搜索树和 AVL 树所需的时间复杂度之间的差异?

c++ - 查找字符数组中的数字总和

c++ - 检测应用挂起

c++ - 如何按一个值属性对海量 map 进行排序?

python - 基于无组织表创建字典的SQL语句

c# - 使用 C# 排列多个字典值