【Tire 求字典出現的字首個數】hihocoder 1014 Trie樹

CN_swords發表於2017-08-21

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;
}


相關文章