首页 > 代码库 > hihoCoder #1014 Trie树

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\n", ret);    }    deleteTrie(pTree);    return 0;}
View Code

hihoCoder #1014 Trie树