0
点赞
收藏
分享

微信扫一扫

字典树模板


动态字典树:

//好写,速度稍慢
const int N = 100000 + 10, INF = 0x3f3f3f3f;
struct trie
{
    int val;
    trie *next[26];
    trie()
    {
        val = 0;
        memset(next, 0, sizeof next);
    }
}*root; //字典树根,记得初始化根
void trie_insert(char *s)
{
    trie *p = root;
    for(int i = 0; s[i]; i++)
    {
        int j = s[i] - 'a';
        if(p->next[j] == NULL) p->next[j] = new trie;
        p->next[j]->val++;//模板代码是求前缀为给定字符串的字符串个数
        p = p->next[j];
    }
}
int trie_query(char *s)
{
    trie *p = root;
    for(int i = 0; s[i]; i++)
    {
        int j = s[i] - 'a';
        if(p->next[j] == NULL) return 0;
        p = p->next[j];
    }
    return p->val;
}
//调用此函数传入字典树根root,清空当前字典树,多实例一定要清空,单实例无所谓
void trie_del(trie *p) 
{
    for(int i = 0; i < 26; i++)
        if(p->next[i] != NULL) trie_del(p->next[i]);
    delete p;
}

静态字典树:

//速度稍快,小心空间大小问题,容易RE或MLE
const int N = 100000 + 10;
struct node
{
    int val;
    node *next[26];
}trie[N*10], *root;
int tot;
char s[N];
node* node_init()
{
    trie[tot].val = 0;
    memset(trie[tot].next, 0, sizeof trie[tot].next);
    return trie + tot++;
}
void trie_init() //初始化,清空字典树,代价O(1)
{
    tot = 0;
    root = node_init();
}
void trie_insert(char *s)
{
    node *p = root;
    for(int i = 0; s[i]; i++)
    {
        int j = s[i] - 'a';
        if(p->next[j] == NULL) p->next[j] = node_init();
        p->next[j]->val++;//模板代码是求前缀为给定字符串的字符串个数
        p = p->next[j];
    }
}
int trie_query(char *s)
{
    node *p = root;
    for(int i = 0; s[i]; i++)
    {
        int j = s[i] - 'a';
        if(p->next[j] == NULL) return 0;
        p = p->next[j];
    }
    return p->val;
}


举报

相关推荐

0 条评论