hdu1072 What Are You Talking About (字典树)

本文介绍了一种使用字典树(Trie)的数据结构来实现简单翻译系统的算法。通过构建字典树,系统能够高效地插入和查询单词,进而完成从一种语言到另一种语言的翻译任务。文章提供了完整的C语言代码实现,并展示了如何处理输入字符串,进行单词分割及翻译。

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

题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1075


题解:套字典树模版即可


#include <stdio.h>    
#include <stdlib.h>    
#include <string.h>
#define MAXN 50002  

typedef struct node    
{    
	struct node *child[26];//存储下一个字符    
	int cnt;//该节点是否是单词的结尾  
	char tranl[12];//翻译
}node,*Trie;    

Trie root;//字典树的根节点    


void insert(char *str,char *word)    
{    
	int i,j,index,len;    
	Trie current,newnode;    
	len=strlen(str);    
	if(len==0)    
		return;//单词长度为0    
	current=root;//当前节点为根节点    
	for(i=0;i<len;++i)    
	{    
		index=str[i]-'a';    
		if(current->child[index]!=NULL)//字典树存在该字符    
		{    
			current=current->child[index];     
		}    
		else    
		{    
			newnode=(struct node *)malloc(sizeof(struct node));//新增一节点    
			for(j=0;j<26;++j)    
				newnode->child[j]=NULL;    
			newnode->cnt=0;
			strcpy(newnode->tranl,"");
			current->child[index]=newnode;    
			current=newnode;//修改当前节点    
		}    
	}   
	current->cnt=1;//该节点是单词的尾  
	strcpy(current->tranl,word);
}    

void query(char *str,char *word)    
{    
	int i,index,len,ans; 
	Trie current;    
	len=strlen(str);    
	if(len==0)    
	{
		strcpy(word,str);
		return ;
	}
	current=root;//从根节点开始查找    
	for(i=0;i<len;++i)    
	{    
		index=str[i]-'a';    
		if(current->child[index]==NULL)  
		{
			strcpy(word,str);
			return;//字典树不存在此单词
		}
		else
		{
			current=current->child[index]; 
		}
	}
	if(current->cnt==1)//字典树存在该单词
		strcpy(word,current->tranl);
	else
		strcpy(word,str);
}

void Del(Trie root)//释放内存    
{    
	int i;    
	if(root==NULL)    
		return;    
	for(i=0;i<26;++i)    
	{    
		if(root->child[i]!=NULL)    
			Del(root->child[i]);    
	}    
	free(root);    
	root=NULL;    
}    

int main()    
{    
	int i,j; 
	char str1[12],str2[12],book[3002],temp[12];
	root=(struct node *)malloc(sizeof(struct node));    
	for(i=0;i<26;++i)    
		root->child[i]=NULL;    
	root->cnt=0; 
	strcpy(root->tranl,"");
	scanf("%s",str1);
	while(scanf("%s",str1))
	{
		if(!strcmp(str1,"END"))
			break;
		scanf("%s",str2);
		insert(str2,str1);
	}
	scanf("%s",str1);
	getchar();
	while(1)
	{
		gets(book);
		if(!strcmp(book,"END"))
			break;
		for(i=0,j=0;book[i]!='\0';++i)
		{
			if(book[i]>='a'&&book[i]<='z')
				temp[j++]=book[i];
			else
			{
				temp[j]='\0';
				query(temp,str2);
				printf("%s",str2);
				printf("%c",book[i]);//符号空格不需要翻译,所以直接输出.
				j=0;
			}
		}
		printf("\n");
	}
	Del(root);    
	return 0;    
}   


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值