zoukankan      html  css  js  c++  java
  • hihoCoder #1014 Trie树

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

    #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
    ", ret);
        }
    
        deleteTrie(pTree);
        return 0;
    }
    View Code
  • 相关阅读:
    PPT图片
    饥荒Steam相关mod代码
    Ubuntu20.04更换阿里源 source.list文件
    中断处理与进程调度的区别与联系
    原语和系统调用的区别
    立下个flag,这个月底之前要发一个深度学习入门系列的文章
    conda安装skimage
    机器学习入门(三)
    zip安装的MySQL绑定my.ini配置文件
    Anaconda配置安装
  • 原文地址:https://www.cnblogs.com/tonix/p/4141905.html
Copyright © 2011-2022 走看看