【POJ】2503 Babelfish(字典树,map,指针)

一、map

输入时候的格式有点难想,还有一种想法是用gets读取,然后用sscanf分开,分别存到两个数组中去,再加入map中,但是这一种方法目前还没有实现。。

#include <iostream>
#include <cstring>
#include <string>
#include <map>
#include <algorithm>
using namespace std;

int main ()
{
	string s1,s2;
	char a[1000],b[1000];
	char t;
	map<string,string> m;
	while(true)
	{
		int i=0;
		t=getchar();
		if(t=='\n')
			break;
		else
		{
			a[i++]=t;
			while(true)
			{
				if((t=getchar())==' ')
				{
					a[i]='\0';
					break;
				}
				else
					a[i++]=t;
			}
			scanf("%s",b);
			getchar();
			m[b]=a;
		}
	}
	char c[1000];
	map<string,string>::iterator it;
	while(scanf("%s",c)!=EOF)
	{
		it=m.find(c);
		if(it!=m.end())
			cout << m[c] << endl;
		else
			cout << "eh\n";
	}
	return 0;
}

二、链表

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
 
typedef struct node
{
	char *str;
	node *next[26];
	node()
	{
		str = NULL;
		for(int i=0;i<26;i++)
			next[i] = NULL;
	}
}N ;
N *root;
 
void insert(char *word,char *trans)
{
	N *p=root;
	for(int i=0;word[i];i++)
	{
		int x = word[i] - 'a';
		if(p->next[x]==NULL)
			p->next[x] = new N;
		p=p->next[x];
	}
	p->str = new char[12];
	strcpy(p->str,trans);
}
 
void find(char *word)
{
	N *p=root;
	for(int i=0;word[i];i++)
	{
		int x = word[i]-'a';
		if(p->next[x]==NULL)
		{
			printf("eh\n");
			return ;
		}
		p=p->next[x];
	}
	if(p->str!=NULL)
		printf("%s\n",p->str);
	else
		printf("eh\n");
}

void del_node(N *root)
{
	for(int i=0;i<26;i++)
	{
		if(root->next[i]!=NULL)
			del_node(root->next[i]);
	}
	delete(root);
}
 
int main ()
{
	char s[25],word[12],trans[12];
	root = new N;
	while(gets(s))
	{
		if(s[0]=='\0')
			break;
		sscanf(s,"%s%s",trans,word);
		insert(word,trans);
	}
	while(scanf("%s",s)!=EOF)
		find(s);
	del_node(root);
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值