hihoCoder week2 Trie树

题目链接

https://hihocoder.com/contest/hiho2/problems

 

字典树

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

struct node{
    node *nex[26];
    int num;
    node(){
        num=0;
        for(int i=0;i<26;i++) 
            nex[i]=NULL;
    }
};


const int N = 50;
char s[N]; int n,m; node *root;

void ins(char *s, int len)
{
    node *rt=root;
    for(int i=0; i<len; i++) {
        int x = s[i]-'a';
        if(rt->nex[x]==NULL) 
            rt->nex[x]=new node();
        rt = rt->nex[x];
        rt->num ++;
    }
    //rt->num++;
    return ;
}

int query(char *s, int len) {
    node *rt = root;
    for(int i=0; i<len; i++) {
        int x = s[i]-'a';
        if(rt->nex[x]==NULL)
            return 0;
        rt = rt->nex[x];
    }
    if(rt != NULL)
        return rt->num;
    return 0;
}

int main()
{
    freopen("in.txt","r",stdin);
    scanf("%d", &n);
    root = new node();
    for(int i=0;i<n;i++) {
        scanf("%s",s);
        int l = strlen(s);
        ins(s, l);
    }
    scanf("%d", &m);
    while(m--) {
        scanf("%s",s);
        int l = strlen(s);
        int ans = query(s,l);
        printf("%d\n",ans);
    }
    return 0;
}

 

posted @ 2018-11-06 15:19  Draymonder  阅读(135)  评论(0)    收藏  举报