hdu4287Intelligent IME 字典树

思路:把后面的字符串转换为数字加入到字典树中,然后再重新检索一下原来的数字的个数

注意:由于有多个实例,所以每个实例结束后必须清空一下字典树

#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
#define NSIZ 5010
#define WS   100
#define N    8
char words[NSIZ][N];
typedef struct Node_
{
	struct Node_ * next[10];
	int    isWord;
	int    id;
	Node_()
	{
		for (int i = 0;i < 10; i++)
		{
			next[i] = 0;
		}
		isWord = 0;
		id = -1;
	}
}Node;
Node * root = 0;
int m_hash[256];
bool InsertTree(char * word)
{
	if (!word || word[0] == 0)
	{
		return 0;
	}
	if (!root)
	{
		root = new Node();
	}
	int i = 0, locate = 0, n = strlen(word);
	Node * tmp = root;
	for (i = 0;i < n; ++i)
	{
		locate = word[i] - '0';
		if (tmp->next[locate] == 0)
		{
			tmp->next[locate] = new Node();
		}
		tmp = tmp->next[locate];
	}
	tmp->isWord++;
	return 0;
}

int SearchTree(char * word)
{
	if (!word || word[0] == 0 || !root)
	{
		return 0;
	}
	int i = 0, locate = 0, n = strlen(word);
	Node * tmp = root;
	for (i = 0;i < n; ++i)
	{
		locate = word[i] - '0';
		if (tmp->next[locate] == 0)
		{
			printf("0\n");
			return 0;
		}
		tmp = tmp->next[locate];
	}
	printf("%d\n", tmp->isWord);
	return 1;
}
bool DeleteTree(Node * root)
{
	if (!root)
	{
		return 0;
	}
	int i = 0;
	for (i  = 0;i < 26; ++i)
	{
		if (root->next[i] == 0)
		{
			Node * tmp = root->next[i];
			DeleteTree(tmp);
		}
	}
	if (root)
	{
		delete root;
		root = 0;
	}
	return 1;
}
void Init()
{
	m_hash['a'] = 2;
	m_hash['b'] = 2;
	m_hash['c'] = 2;
	m_hash['d'] = 3;
	m_hash['e'] = 3;
	m_hash['f'] = 3;
	m_hash['g'] = 4;
	m_hash['h'] = 4;
	m_hash['i'] = 4;
	m_hash['j'] = 5;
	m_hash['k'] = 5;
	m_hash['l'] = 5;
	m_hash['m'] = 6;
	m_hash['n'] = 6;
	m_hash['o'] = 6;
	m_hash['p'] = 7;
	m_hash['q'] = 7;
	m_hash['r'] = 7;
	m_hash['s'] = 7;
	m_hash['t'] = 8;
	m_hash['u'] = 8;
	m_hash['v'] = 8;
	m_hash['w'] = 9;
	m_hash['x'] = 9;
	m_hash['y'] = 9;
	m_hash['z'] = 9;
}

int main()
{
	int i = 0, n = 0,t,  n1, j, m, k;
	char word1[N];
	char word2[N];
	Init();
	while (scanf("%d", &t) != EOF )
	{
		while(t--)
		{
			scanf("%d %d", &n, &m);
			for (i = 0;i < n; ++i)
			{
				scanf("%s", words[i]);
			}
			root = 0;
			for (i = 0;i < m;++i)
			{
				scanf("%s", word1);
				n1 = strlen(word1);
				for (j = 0; j < n1; ++j)
				{
					word2[j] = m_hash[word1[j]] + '0';
				}
				word2[j] = 0;
				InsertTree(word2);
			}
			for (i = 0;i < n; ++i)
			{
				SearchTree(words[i]);
			}
			DeleteTree(root);
		}
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值