【Tire 求字典出现的前缀个数】hihocoder 1014 Trie树

Link:http://hihocoder.com/problemset/problem/1014

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;

const int N = 1e5+5;
const int M = 26;
struct Tire{
    struct Node{
        int nex[M];
        int endd;
    }node[N*20];
    int Size;

    int newnode(){
        for(int i = 0; i < M; i++)
            node[Size].nex[i] = 0;
        node[Size].endd = 0;
        return Size++;
    }

    void init(){
        Size = 0;
        newnode();
    }

    void Insert(char *s){
        int len = strlen(s);
        int now = 0;
        for(int i = 0; i < len; i++){
            int x = s[i]-'a';
            if(node[now].nex[x]==0)
                node[now].nex[x]=newnode();
            now = node[now].nex[x];
            node[now].endd ++;
        }
    }

    int marth(char *s){
        int len = strlen(s);
        int now = 0, i;
        for(i = 0; i < len; i++){
            int x = s[i]-'a';
            if(node[now].nex[x]==0)
                break;
            now = node[now].nex[x];
        }
        if(i == len) return node[now].endd;
        else return 0;
    }
}tire;

char s[20];
int main()
{
    int n,m;
    scanf("%d",&n);
    tire.init();
    for(int i = 1; i <= n; i++)
        scanf("%s",s), tire.Insert(s);
    scanf("%d",&m);
    for(int i = 1; i <= m; i++)
        scanf("%s",s), printf("%d\n",tire.marth(s));
    return 0;
}

    原文作者:Trie树
    原文地址: https://blog.csdn.net/qq_33199236/article/details/77449222
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞