HDU_1804_Deli Deli (字典树)

本文介绍了一种使用字典树结构处理英语不规则复数单词的方法,通过添加和查询功能,实现对特定单词复数形式的高效检索。该算法特别针对英语中常见的不规则复数变化规律进行优化。

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

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


#include <stdio.h>
#include <string.h>
const int words_max_length = 23;  //单词的最大长度,题目给的是20

struct node{
	node * child[26];
	char word[words_max_length];
	node(){memset(child, 0, sizeof(child)); memset(word, 0, sizeof(word));}
}* root = new node(); // 先建立一个全局的根结点

void add_word(char * before, char * after)
{
	//往字典树中加入数据,before是要检索的单词,after是最终结点中的数据,也就是对应不规则单词的复数形式
	node * next = root;
	while(*before)
	{
		if(next->child[*before-'a'] == NULL)
			next->child[*before-'a'] = new node();
		next = next->child[*before-'a'];
		before++;
	}
	strcpy(next->word, after);
}

char * query(char * str)
{
	//查询不规则复数单词表,返回的是单词的首地址,如果没有,返回空
	node * next = root;
	while(*str)
	{
		if(next->child[*str-'a'] == NULL)
			return NULL;
		next = next->child[*str-'a'];
		str++;
	}
	return next->word;
}
int main()
{
	//freopen("E:\\input.txt", "r", stdin);
	int n, m;
	scanf("%d %d", &n, &m);

	char before[words_max_length], after[words_max_length];
	while(n--)
	{
		scanf("%s %s", before, after);
		add_word(before, after);
	}
	while(m--)
	{
		scanf("%s", before);
		int len = strlen(before);
		char * sptr = query(before);
		//strcpy(after, query(before));
		if(sptr != NULL)
			printf("%s\n", sptr);
		else if( (before[len-1] == 'y') && 
			 (before[len-2] != 'a' && before[len-2] != 'e' && 
			  before[len-2] != 'i' && 
		 	  before[len-2] != 'o' && before[len-2] != 'u') )
		{
			before[len-1] = 'i';
			printf("%ses\n", before);
		}
		else if( (before[len-1]=='o') || 
			 (before[len-1]=='s') ||
			 (before[len-1]=='x') ||
			 (!strcmp(&before[len-2], "ch")) ||
			 (!strcmp(&before[len-2], "sh")) )
			printf("%ses\n", before);
		else
			printf("%ss\n", before);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值