Trie树初学

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
const int root=0;
int tot;
struct node
{
    int cnt;
    int next[26];
    void newnode()
    {
        cnt=0;
        for(int i=0;i<26;i++)
        {
            next[i]=-1;
        }
    }
}t[1000005];
void clear()
{
    tot=0;
    t[root].newnode();
}
void insert(char *str)
{
    int p=root;
    int len=strlen(str);
    for(int i=0;i<len;i++)
    {
        int id=str[i]-'a';
        if(t[p].next[id]==-1)
        {
            t[++tot].newnode();
            t[p].next[id]=tot;
        }
        p=t[p].next[id];
        t[p].cnt++;
    }
}
int query(char *str)
{
    int p=root;
    int len=strlen(str);
    for(int i=0;i<len;i++)
    {
        int id=str[i]-'a';
        if(t[p].next[id]==-1)
        {
            return 0;
        }
        p=t[p].next[id];
    }
    return t[p].cnt;
}
int main()
{
    int n,m;
    char s[15];
    clear();
    scanf("%d",&n);
    while(n--)
    {
        scanf("%s",s);
        insert(s);
    }
    scanf("%d",&m);
    while(m--)
    {
        scanf("%s",s);
        printf("%d
",query(s));
    }
    return 0;
}
原文地址:https://www.cnblogs.com/wikioibai/p/4471483.html