北大ACM2503——Babelfish~~字典树的应用

题目的意思是:给你几个字符串对str1,str2。输入完毕后有一个空行,然后是询问的输入,每行一个字符串,如果该字符串与str2相同,则输出str1,否则输出“eh”。

这题字符串对达到100000,询问的也达到了100000个,所以,普通的方法必定超时。所以需要建立字典树。

这题还有一个比较麻烦的就是输入。如何控制那一个空行之后的询问输入,这是关键。

简单的字典树的应用。

下面是AC的代码:

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

class node
{
public:
	node* ch[28];
	char str[12];
	node()
	{
		memset(ch, NULL, sizeof(ch));
		memset(str, '\0', sizeof(str));
	}
};
node *root;

void insert(char* str1, char* str2)   //建树
{
	int length = strlen(str1);
	node *temp = root;
	for(int i = 0; i < length; i++)
	{
		if(temp->ch[str1[i] - 'a'] == NULL)   //该位置为空,new一个
		{
			temp->ch[str1[i] - 'a'] = new node();
			temp = temp->ch[str1[i] - 'a'];
		}
		else                                   //否则,等于它的后继
			temp = temp->ch[str1[i] - 'a'];
		if(i == length - 1)                     //到达字符串的结尾,将与之相关联的str赋值给叶子节点
			strcpy(temp->str, str2);
	}
}
void finds(char* str)          //查找
{
	int length = strlen(str);
	node *temp = root;
	for(int i = 0; i < length; i++)
	{
		if(temp->ch[str[i] - 'a'] != NULL)
		{
			temp = temp->ch[str[i] - 'a'];
		}
		else
		{
			cout << "eh" << endl;
			return;
		}
	}
	cout << temp->str << endl;
}

int main()
{
	char str1[15], str2[15], str[30];
	int i, j;
	root = new node();
	while(gets(str))           //输入的格式
	{
		if(strlen(str) == 0)  //如果为空行,退出
			break;
		i = 0; j = 0;
		while(str[i] != ' ')
			str1[j++] = str[i++];
		str1[j] = '\0'; i++;
		j = 0;
		while(str[i] != '\0')
			str2[j++] = str[i++];
		str2[j] = '\0';
		insert(str2, str1);
	}
	while(cin >> str)
	{
		finds(str);
	}
	return 0;
}


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值