码迷,mamicode.com
首页 > 其他好文 > 详细

Trie树

时间:2014-07-13 17:17:39      阅读:336      评论:0      收藏:0      [点我收藏+]

标签:http   os   for   io   new   re   

字典树查询

#include<iostream>
#include<cstring>
#include<malloc.h>

using namespace std;

const int maxn = 30;

typedef struct Trie{
	int v;
	Trie *next[ maxn ];
}Trie;

Trie root;

void CreateTrie( char *str ){
	int len = strlen( str );
	//cout << str << endl;
	Trie *p = &root, *q;
	for( int i = 0; i < len; ++i ){
		int id = str[ i ] - 'a';
		if( p -> next[ id ] == NULL ){
			//q = new Trie;
			q = ( Trie * )malloc( sizeof( root ) );
			for( int j = 0; j < maxn; ++j ){
				q -> next[ j ] = NULL;
			}
			q -> v = 1;
			p  -> next[ id ] = q;
		}
		else{
			p -> next[ id ] -> v++;
		}
		p = p -> next[ id ];
	}
}

int FindTrie( char *str ){
	int len = strlen( str );
	Trie *p = &root;
	for( int i = 0; i < len; ++i ){
		int id = str[ i ] - 'a';
		if( p -> next[ id ] == NULL ){
			return 0;
		}
		p = p -> next[ id ];
	}
	return p -> v;
}


int main(){
	int n, m;
	char str[ maxn ];
	for( int i = 0; i < maxn; ++i ){
		root.next[ i ] = NULL;
	}
	cin >> n;
	while( n-- ){
		cin >> str;
		CreateTrie( str );
	}
	memset( str, 0, sizeof( str ) );
	cin >> m;
	while( m-- ){
	cin >> str;
		int ans = FindTrie( str );
		cout << ans << endl;
	}
	return 0;
}

/*
5
banana
band
bee
absolute
acm

4
ba
b
band
abc






2
3
1
0 
*/


Trie树,布布扣,bubuko.com

Trie树

标签:http   os   for   io   new   re   

原文地址:http://blog.csdn.net/bo_jwolf/article/details/37737757

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!