码迷,mamicode.com
首页 > 其他好文 > 详细

trie树

时间:2015-11-20 17:01:23      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:

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

 

trie树

标签:

原文地址:http://www.cnblogs.com/zendu/p/4980974.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!