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

hihoCoder #1014 Trie树

时间:2014-12-04 06:18:38      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   for   

没什么难的,提示已经说得很明白了。HihoCoder目前还不支持C++11,囧..

bubuko.com,布布扣
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
#include <map>

using namespace std;

//
struct Node
{
    Node(char rc) : c(rc), count(0) {};
    char c;
    map<char, Node *> child;
    int count;
};
Node *pTree = 0;
//

void incBuild(string &s)
{
    Node *pc = pTree;
    for(int i = 0; i < s.length(); i ++)
    {
        char c= s[i];
        if(pc->child.find(c) == pc->child.end())
        {
            Node *pNew = new Node(c);
            pc->child.insert(make_pair(c, pNew));
        }
        pc = pc->child[c];
        pc->count ++;
    }
}

void deleteTrie(Node *p)
{
    queue<Node *> q; q.push(p);
    while(!q.empty())
    {
        Node *pc = q.front(); q.pop();        
        typedef std::map<char, Node *>::iterator it_type;
        for(it_type it = pc->child.begin(); it != pc->child.end(); it++)
        {
            q.push(it->second);
        }
        delete pc;
    }
}

//
int query(string &s) 
{    
    Node *pc = pTree;
    for(int i = 0; i < s.length(); i ++)
    {
        char c= s[i];
        if(pc->child.find(c) == pc->child.end())
        {
            return 0;
        }
        pc = pc->child[c];        
    }
    return pc->count;
}

//
const int MAX_LEN = 100001;
int main()
{
    char buf[MAX_LEN] = {0};

    pTree = new Node(0);

    //    Get input
    int n; scanf("%d", &n);
    while (n--)
    {
        memset(buf, MAX_LEN, 0);
        scanf("%s", buf);

        string in(buf);
        incBuild(in);
    }

    //    Query
    scanf("%d", &n);
    while (n--)
    {
        memset(buf, MAX_LEN, 0);
        scanf("%s", buf);

        string qs(buf);
        int ret = query(qs);
        printf("%d\n", ret);
    }

    deleteTrie(pTree);
    return 0;
}
View Code

hihoCoder #1014 Trie树

标签:style   blog   http   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/tonix/p/4141905.html

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