hihoCoder #1014 : Trie树

题目分析

统计以某字符串为前缀的单词的数量,首先建立字典树,注意字典树的点数为100000,同时是由小写字母都成的,我们用val作为标记数组,每当有单词从这个位置走过那么我们就加一,那么val表示的意思就是以该前缀的单词的数量,遍历一下找到最后一个点就可以了,详细请看代码。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxnode = 1000005;
const int sigma_size = 27;

struct Trie
{
    int ch[maxnode][sigma_size];
    int val[maxnode];
    int sz;
    Trie() {sz = 1; memset(ch[0], 0, sizeof(ch[0]));}
    int idx(char c) {return c - 'a';}
    void Insert(char *s)
    {
        int u = 0,n = strlen(s);
        for(int i = 0; i < n; i++)
        {
            int c = idx(s[i]);
            if(!ch[u][c])
            {
                memset(ch[sz], 0, sizeof(ch[sz]));
                val[sz] = 1;
                ch[u][c] = sz++;
                u = ch[u][c];
            }
            else
            {
                u = ch[u][c];
                val[u]++;
            }
        }
    }

    int Inquire(char *s)
    {
        int u = 0,n = strlen(s);
        for(int i = 0; i < n; i++)
        {
            int c = idx(s[i]);
            if(!ch[u][c])
                return 0;
            else
                u = ch[u][c];
        }
        return val[u];
    }
};
Trie trie;

int main()
{
    int n,m;
    char str[15];
    scanf("%d", &n);
    while(n--)
    {
        scanf("%s", str);
        trie.Insert(str);
    }
    scanf("%d", &m);
    while(m--)
    {
        scanf("%s", str);
        printf("%d\n", trie.Inquire(str));
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值