hihocoder-1014 Trie树

hihocoder 1014 : Trie树

link: https://hihocoder.com/problemset/problem/1014

题意:

实现Trie树,实现对单词的快速统计。

#include <iostream> 
#include <cstdio> 
using namespace std; 

typedef struct TrieNode{
	int cnt; 
	struct TrieNode *next[26];  
}TrieNode; 

TrieNode memory[2000000]; 
int alloop = 0; 

TrieNode* createNode(){
	TrieNode* node = &memory[alloop++]; 
	node->cnt = 1; 
	for(int i=0; i<26; ++i){
		node->next[i] = NULL; 
	}
	return node; 
}

void InsertNode(TrieNode *root, char *c){
	TrieNode *cur = root; 
	for(int i=0; c[i]; ++i){
		if(cur->next[c[i]-'a'] == NULL){
			cur->next[c[i]-'a'] = createNode(); 
		}else{	
			cur->next[c[i]-'a']->cnt += 1; 
		}
		cur = cur->next[c[i]-'a']; 
	}
}

int SearchNode(TrieNode* root, char *c){
	TrieNode* cur = root; 
	for(int i=0; c[i]; ++i){
		cur = cur->next[c[i]-'a']; 
		if(cur == NULL){
			return 0; 
		}
	}
	return cur->cnt; 
}

int main(){
	freopen("in.txt", "r", stdin); 

	int n,m, ans; 
	char st[12]; 
	TrieNode* root = createNode(); 
	root->cnt = 0; 
	scanf("%d", &n); 
	for(int i=0; i<n; ++i){
		scanf("%s", st); 
		getchar(); 
		InsertNode(root, st); 
	}
	scanf("%d", &m); 
	for(int i=0; i<m; ++i){
		scanf("%s", st);
		getchar();  
		ans = SearchNode(root, st); 
		printf("%d
", ans);
	}
	return 0; 
}

  

原文地址:https://www.cnblogs.com/zhang-yd/p/6038365.html