Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trie Implementation With Map

i was working solving a problem today. But i got stucked. I know how a trie works but the problem is that i know how to implement it with static arrays and classes. Today surfing on the web i read that there is a way to implement tries using stl::map. I tried today but i still dont know how to insert elements on int. this struchture.

Edit1: i am trying to solve this problem :spoj.com/problems/TAP2012D I want to know how to add the words in to the trie with edit2: I know how a map works, i just dont know how a trie with a map works. I want someone that knows about tries.

Here is what ive done so far

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]]=
        }

    }

}
like image 769
Giuseppe Avatar asked Feb 15 '13 02:02

Giuseppe


2 Answers

A trie node stores a map of existing out characters and a flag indicating if the node corresponds to a word in the trie.

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

    Node() { flag = false; }
};

Now insertion is similar to what you'd do with a static array, except that you are using a map here.

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 */
}
like image 82
mrk Avatar answered Oct 11 '22 09:10

mrk


Using an unordered_map is better in my opinion.

    struct TrieNode {
        char c;
        unordered_map<char, TrieNode*>links;
        bool end;
    };

    TrieNode* insert(TrieNode* root, string word) {
        TrieNode* current  = root;

        for (auto it: word) {
           if (current->links.find(it) == current->links.end()) {
           TrieNode* node = new TrieNode(); // possible memory leak?
           node->c = it;
           node->links = {};
           node->end = false;

           current->links[it] = node;
           }

        current = current->links[it];
       }

    current->end = true;
    return root;
    };

Ofcourse, there could be an issue of having memory leaks with the TrieNodes that you create with the new operator. Maybe some sort of a tree traversal (DFS based) to visit all the nodes in a bottom up fashion and deleting them, could help one avoid memory leaks.

like image 35
Saurav Biswas Avatar answered Oct 11 '22 09:10

Saurav Biswas