静态字典树模板

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

int pos;

struct node
{
    int child[26];
}tree[10000010];

int add()
{
    pos++;
    for(int i=0;i<26;i++)
    {
        tree[pos].child[i]=-1;
    }
    return pos;
}

int inser(char* str)
{
    int post=0;
    int tmp=0;
    int len=strlen(str);
    for(int i=0;i<len;i++)
    {
        int m=str[i]-'a';
        if(tree[post].child[m]==-1)
        {
            if(tmp==0)
                tmp=i+1;
            tree[post].child[m]=add();
        }
        post=tree[post].child[m];
    }
    if(!tmp)
        tmp=len;
    return tmp;
}

char arr[1000010];
int main()
{
    int T;
    scanf("%d",&T);
    for(int t=1;t<=T;t++)
    {
        int n;
        pos=0;
        memset(tree[0].child,-1,sizeof(tree[0].child));
        scanf("%d",&n);
        int ans=0;
        for(int i=0;i<n;i++)
        {
            scanf("%s",&arr);
            int k=inser(arr);
            ans+=k;
        }
        cout<<"Case #"<<t<<": "<<ans<<endl;
    }
    return 0;
}

静态字典树比动态字典树节省时间,动态字典树创建指针的过程太浪费时间

原文地址:https://www.cnblogs.com/wsruning/p/5663038.html