【字典树】hdu 4287 Intellident IME

本文介绍了一种使用字典树和哈希表实现的电话号码匹配算法。该算法能够高效地处理大量的电话号码映射关系,并快速查找匹配项。文中提供了完整的C++实现代码,包括字典树的构建、搜索及删除操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://acm.hdu.edu.cn/showproblem.php?pid=4287

分析:

赶脚这样的数据:

1 1

23

adsss

答案:0


效率比较(hash、字典树):


字典树(加了判断,是否为整个单词):

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

const int NM=5005;
char strn[NM][10],str[NM][10];
int map[30]={2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9};

struct Node{
	Node *next[10];
	int ccount;
	bool tail;  //

	Node(){
		for(int i=0;i<10;i++)
			next[i]=NULL;
		ccount=0;
		tail=false;
	}
};

void BuildT(Node *tree,char *s1)
{
	int i,len,t;
	len=strlen(s1);
	for(i=0;i<len;i++)
	{
		t=map[s1[i]-'a'];
		if(tree->next[t]==NULL)
			tree->next[t]=new Node();
		tree=tree->next[t];
		tree->ccount++;
	}
	tree->tail=true;
}

int SearchT(Node *tree,char *s2)
{
	int i,len,t;
	len=strlen(s2);
	for(i=0;i<len;i++)
	{
		t=s2[i]-'0';
		if(tree->next[t]!=NULL)
			tree=tree->next[t];
		else return 0;
	}
	if(tree->tail) return tree->ccount;
	else return 0;
}

void DelT(Node *tree)
{
	for(int i=0;i<10;i++)
		if(tree->next[i]!=NULL)
			DelT(tree->next[i]);
	delete tree;
}

int main()
{
	int i,n,m,T;
	
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d%d",&n,&m);
		Node *p=new Node();
		for(i=0;i<n;i++)
			scanf("%s",strn[i]);
		for(i=0;i<m;i++)
		{
			scanf("%s",str[i]);
			BuildT(p,str[i]);
		}
		
		for(i=0;i<n;i++)
			printf("%d\n",SearchT(p,strn[i]));

		DelT(p);
	}
	return 0;
}

哈希:

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

const int NM=5005;
char str[NM][10];
int hash[1000005],a[NM];
int map[30]={2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9};

int main()
{
	int i,j,n,m,len,t,temp,T;
	
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d%d",&n,&m);
		memset(hash,0,sizeof(hash));
		for(i=0;i<n;i++)
			scanf("%d",&a[i]);
		for(i=0;i<m;i++)
		{
			scanf("%s",str[i]);
			len=strlen(str[i]);
			temp=0;
			for(j=0;j<len;j++)
			{
				t=map[str[i][j]-'a'];
				temp=temp*10+t;
			}
			hash[temp]++;
		}
		
		for(i=0;i<n;i++)
			printf("%d\n",hash[a[i]]);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值