trie树

#include <cstdio>
#include <cstring>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;

const int N = 100010;

struct Tree
{
    int v;
    struct Tree *pchild[26];
    Tree():v(1)
    {
        for(int i=0;i<26;i++)
            pchild[i]=NULL;
    }
}*tree;


void build(Tree *tree,char *s)
{
    tree->v++;
    int len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        int u = s[i]-'a';
        if(tree->pchild[u] == NULL)
        {
            Tree *p = new Tree;
            tree->pchild[u] = p;
        }
        else
        {
            tree->pchild[u]->v++;
        }
        tree = tree->pchild[u];
    }
}

int find(Tree *tree,char *s)
{
    int len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        int u = s[i]-'a';
        if(tree->pchild[u] == NULL)
            return 0;
        if(i+1 == len)
            return tree->pchild[u]->v;
        tree = tree->pchild[u];
    }
}

int main()
{
    int n,m;
    tree = new Tree();

    tree->v = 0;
    scanf("%d",&n);
    char a[50];
    for(int i = 0; i < n; i ++)
    {
        scanf("%s",a);
        build(tree,a);
    }
    scanf("%d",&m);
    for(int i = 0; i < m; i ++)
    {
        scanf("%s",a);
        printf("%d
",find(tree,a));
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zendu/p/4980974.html