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\n",find(tree,a));
    }
    return 0;
}
复制代码

 

posted on   zyz913614263  阅读(156)  评论(0)    收藏  举报

编辑推荐:
· 记一次 .NET某固高运动卡测试 卡慢分析
· 微服务架构学习与思考:微服务拆分的原则
· 记一次 .NET某云HIS系统 CPU爆高分析
· 如果单表数据量大,只能考虑分库分表吗?
· 一文彻底搞懂 MCP:AI 大模型的标准化工具箱
阅读排行:
· 博客园2025新款「AI繁忙」系列T恤上架
· Avalonia跨平台实战(二),Avalonia相比WPF的便利合集(一)
· C# LINQ 快速入门实战指南,建议收藏学习!
· Redis实现高并发场景下的计数器设计
· 上周热点回顾(4.7-4.13)
< 2025年4月 >
30 31 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 1 2 3
4 5 6 7 8 9 10

导航

点击右上角即可分享
微信分享提示