Trie 简介

· · 个人记录

0x00 What is Trie?

Actually the word "Trie" is pronounced /tri:/.

"Trie" is short for "reTrieval"(n.search for).It is a tree data structure which can maintain a set of strings, providing a wonderful O(patlen) time complexity of searching a specific pattern in the set by using more(most of the time) space.

0x01 Understanding Trie

In this trie, we stored:

aa
aba
ba
caaa
cab
cba
cc

When we build a Trie, we merge a "chain of characters" with a Trie already exists, removing duplicated parts of the chains' prefix.

For example, merging "character" and "challenge".

character + challenge
cha racter
    llenge

By removing the prefix we can save some space (which sometimes repairs the huge T(charset) pointer space for each node) , and by putting the characters on the edge we can speed up locating a pattern by locating step by turning each character to an array subscript.This is the key of Trie,

0x02 Writing Trie

By Trie's definition we can write the following statement:

struct node
{
    int count;
    node* son[26]; //The size of charset as 26
}*root;

In this structure, \text{\red{count}} stands for the amount of words crossing over it, and \text{\red{son[26]}} stands for the characters appears after this node. E.g. for string "\text{ca}" , node \text{"c"} has a son: node \text{"a"}. So the son[0] of node \text{"c"} should be 1.

We should notice that the size of \text{\red{son[]}} in each node is T(charset) , which is very huge, according to the text above.

For adding a new string to the trie, we create a pointer, sequentially access their longest common prefix, and add new nodes to store the rest of the new string.

Here's the code.

void add(string s)
{
    node *t=root;
    for(int i=0;i<s.length();i++)
    {
            if(t->son[s[i]]!=NULL)
            {
                t=t->son[s[i]];
            }
            else
                {
                t->son[s[i]]=(trie*)malloc(sizeof(struct node));
                    memset(t->son[s[i],0,sizeof(t->son[s[i]]));
                    t=t->son[s[i]];
            }
                t.count++;//a new word passing this node

    }
}

To remove a word from the Trie, we only need to remove 1 from each node's \text{\red{count}} .

void add(string s)
{
    node *t=root;
    for(int i=0;i<s.length();i++)
    {
            t=t->son[s[i]];
                t->count--;
    }
}

In order to try to find whether a pattern pat exists in the Trie, we sequentially access the nodes in pat order, return \text{\red{t->count}} when found and return \text{\red{NULL}} when failed to search.

int query(string s)
{
    node *t=root;
    for(int i=0;i<s.length();i++)
    {
        if(!t->son[s[i]])
            return NULL;
        t=t->son[s[i]];
    }
    return t->count;
}

And also there is a way to implement Trie by simulating linked list by using arrays. Here is the code of AcCoders Contest 4590 A.

#include <bits/stdc++.h>
#define N 1000001
using namespace std;
int trie[N][26],cnt=0;
int tag[N];
void add(string s)
{
    int p=0;
    for(int i=0;i<s.length();i++)
    {
        if(!trie[p][s[i]-'a']) 
        {
            trie[p][s[i]-'a']=++cnt;
        }
        p=trie[p][s[i]-'a'];
        //tag[p]++;
    }
    tag[p]++;
}
int query(string s)
{
    int p=0;
    int i;
    for(i=0;i<s.length();i++)
    {
        if(!trie[p][s[i]-'a'])
            return 0;
        p=trie[p][s[i]-'a'];
    }
    return tag[p];
}

int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        string a,b;
        cin>>a>>b;
        if(a=="I") add(b);
        else cout<<query(b)<<endl;
    }
    return 0;
}

0x03 0-1 Trie

0-1 Trie is a special kind of Trie which its charset includes only [0,1]. By processing 32(64)-bit integers as 0-1 binary strings, the 0-1 Trie can maintain the maximum \text{xor} values in an integer set.

When we \text{xor} two integers, it means we compare their bits, the result is 0 when the same and 1 when not.

For example:

    1100110101
xor 0101111001
=   1001001100

When we want to find the maximum value of an integer \text{xor} with each integers in the set, we only need to reverse it by bits(~ in C++), and access the 0-1 Trie by the reversed value to maximize the result.

Here is the code from AcCoders Contest 4590 C, which asks you to maintain the maximum pair \text{xor} value in a set of integers.

Implemented by arrays.

#include <bits/stdc++.h>
#define N 100001
using namespace std;
int trie[N*32][2],cnt;//Notice that here is N*32.
void add(int k)
{
    int p=0;
    for(int i=31;i>=0;i--)
    {
        bool c=(k>>i)&1;//taking out the bits
        if(!trie[p][c]) trie[p][c]=++cnt;
        p=trie[p][c];
    }
}
int query(int k)
{
    int p=0,ans=0;
    for(int i=31;i>=0;i--)
    {
        bool c=!((k>>i)&1);//reversing by bits.
        if(trie[p][c])
        {
            p=trie[p][c];
            ans=(ans<<1)|1;
        }
        else
        {
            p=trie[p][!c];
            ans<<=1;
        }
    }
    return ans;
}
int main()
{
    int n,a[N];
    cin>>n;
    for(int i=0;i<n;i++)
        cin>>a[i],add(a[i]); 
    int ans=INT_MIN;
    for(int i=0;i<n;i++)
        ans=max(ans,query(a[i]));
    cout<<ans;
    return 0; 
}