首页 > 代码库 > 数据结构模板

数据结构模板

Trie树模板:

const int maxm = 31000;
struct Trie
{
    int numptr;
    struct Node
    {
        Node* son[26];
        int ptr;
        void init()
        {
            CLR(son, (int)NULL);
            ptr = -1;
        }
    } s[maxm], root;

    void init()
    {
        numptr = 0;
        root.init();
    }

    void ins(char *ch, int z)
    {
        Node* ptr = &root;
        for(int i = 0; ch[i] != 0; i++)
        {
            int x = ch[i] - 'a';
            if(ptr->son[x] == NULL)
            {
                s[numptr].init();
                ptr->son[x] = &s[numptr++];
            }
            ptr = ptr->son[x];
        }
        ptr->ptr = z;
    }

    int find(char *ch)
    {
        Node *ptr = &root;
        for(int i = 0; ch[i] != 0; i++)
        {
            int x = ch[i] - 'a';
            if(ptr->son[x] == NULL)
            {
                return -1;
            }
            ptr = ptr->son[x];
        }
        return ptr->ptr;
    }
} trie;