您的位置:首页 > 其它

【hihocoder】1014. Trie树

2015-09-25 16:31 363 查看
Trie树的建立,基本上就是按照深度优先搜索的顺序来进行插入结点。

同时,设定一个label,来记录当前经过该node时有多少结点,便于在

查询的时候,可以直接输出,而不需要再次dfs进行搜索。

/**
*  @author         johnsondu
*  @time           16:24 9th Sep 2015
*  @type           trie tree
*  @url            http://hihocoder.com/problemset/problem/1014 */

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <algorithm>
#include <map>
#include <vector>

using namespace std;

const int MAXN = 105;

struct Trie
{
char ch;
int cnt;
Trie *next[26];
Trie() {
cnt = 0;
for(int i = 0; i < 26; i ++)
next[i] = NULL;
}
};

Trie root;
int ans;

void insertWord(char* str)
{
int len = strlen(str);
Trie *head = &root;
for(int i = 0; i < len; i ++) {
int idx = str[i] - 'a';
if(head->next[idx] == NULL) {
Trie *node = new Trie;
node->ch = str[i];
head->next[idx] = node;
}

head = head->next[idx];
head->cnt ++;
}
}

void queryWord(char *str)
{
Trie* head = &root;
int len = strlen(str);
ans = 0;
for(int i = 0; i < len; i ++) {
int idx = str[i] - 'a';
if(head->next[idx] == NULL) return;
else {
head = head->next[idx];
}
}
ans = head->cnt;

}

int main()
{
char str[MAXN];
int n, m;
cin >> n;
for(int i = 0; i < n; i ++)
{
cin >> str;
insertWord(str);
}

cin >> m;
for(int i = 0; i < m; i ++) {
cin >> str;
ans = 0;
queryWord(str);
cout << ans << endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: