hihoCoder#1014Trie树

来源:互联网 发布:w45ap 软件 编辑:程序博客网 时间:2024/05/13 07:17

题目链接
最近发现hihoCoder上的题目都会用到比较单纯的数学结构和算法,不限LeetCode上那样,有些脑筋急转弯的感觉~
hihoCoder上的题目就像比赛那样,一般会给你一个场景,不同的是,他会在“小hi”和”小ho”的对话之中把模型给建立起来。

这一题就是普通的字典树,具体的介绍可以看维基百科
这篇博客里也有很好的介绍

AC的代码:

#include<iostream>#include<algorithm>#include<queue>#include<vector>#include<cstdio>#include<cstring>#include<cstdlib>using namespace std;#define _length 11struct TrieNode {    int num;    TrieNode* next[26];    TrieNode() {        num = 0;        for(int i = 0;i < 26; ++i) {            next[i] = NULL;        }    }};class TrieTree { public:    TrieTree() {        tree_head = new TrieNode;    }    void Insert(char* str);    int Ask(char* str); private:    TrieNode* tree_head;};void TrieTree::Insert(char* str) {    TrieNode* temp = tree_head;    for(int i = 0; str[i]; ++i) {        int tmp = str[i] - 'a';        if (temp->next[tmp] == NULL)            temp->next[tmp] = new TrieNode;        temp = temp->next[tmp];        temp->num++;    }}int TrieTree::Ask(char* str) {    TrieNode* temp = tree_head;    for(int i = 0; str[i]; ++i){        int tmp = str[i] - 'a';        if (temp->next[tmp]==NULL) return 0;            temp = temp->next[tmp];    }    return temp -> num;}int main (int args, char* argv[]){    //freopen("F:/in.txt","r",stdin);    int words_count, ask_count;    scanf("%d", &words_count);    TrieTree mytree;    char word[_length];    for(int i =0; i< words_count; i++) {        cin >> word;        mytree.Insert(word);    }    cin >> ask_count;    char str[_length];  for (int i = 0; i < ask_count; ++i) {        cin >> str;        int num = mytree.Ask(str);        cout << num << endl;  }    //fclose(stdin);    return 0;}这里我一开始偷懒,把里面的char字符数组 用string类型代替,可是一直内存泄露,弄得我崩溃。。。
0 0