hdu 1075 字典树 和 map做法

开始写的时候

Runtime Error

(ACCESS_VIOLATON)

苦逼死了。主要是因为刚学trie吧。

附上代码  trie

#include <cstdio>
#include <string>
#include <stdlib.h>
using namespace std;
typedef struct note
{
	char ch[20];  //储存字符串
	bool ok;
	struct note *next[26];
}trie;
void insert(trie *root,const char *ch1,const char *ch2)
{
	trie *p=root;
	while(*ch2!='\0')
	{
		if(p->next[*ch2-'a']==NULL)
		{
			trie *temp=(trie *)malloc(sizeof(trie));
			temp->ok=false;
			for(int i=0;i<26;i++)
				temp->next[i]=NULL;
			p->next[*ch2-'a']=temp;
		}
		p=p->next[*ch2-'a'];
		ch2++;
	}
	p->ok=true;
	strcpy(p->ch,ch1);  
}
void search(trie *root,const char *ch)
{
	trie *p=root;
	const char *ch1=ch;
	while(p!=NULL&&*ch!='\0')
	{
		p=p->next[*ch-'a'];
		ch++;
	}
	if(p&&p->ok==true&&p->ch)
		printf("%s",p->ch);
	else
		while(*ch1!='\0')
		{
			printf("%c",*ch1);
			ch1++;
		}
}
int main()
{
	trie *root=(trie *)malloc(sizeof(trie));
	root->ok=false;
	for(int i=0;i<26;i++)
		root->next[i]=NULL;
	char ch1[20],ch2[20],str[3500];
	scanf("%s",ch1);
	while(scanf("%s",ch1),strcmp(ch1,"END")!=0)  
    {  
        scanf("%s",ch2);  
        insert(root,ch1,ch2);  
    }
	scanf("%s",ch2); 
	getchar();  
	while(gets(str),strcmp(str,"END")!=0) 
    {  
		char temp[20];
		int k=0;
		for(int i=0;i<strlen(str);i++)
		{
			if(islower(str[i])) temp[k++]=str[i];
			else
			{
				temp[k]='\0';
				search(root,temp);   //该处输出单词
				printf("%c",str[i]);   //能进else说明有字符。直接输出。可能temp没有。但是也无妨。search没输出。
				k=0;
				memset(temp,0,sizeof(temp));
			}
		}
		printf("\n");
    }  
	return 0;
}


map 做法

#include <cstdio>
#include <string>
#include <iostream>
#include <stdlib.h>
#include <map>
using namespace std;
int main()
{
	map<string,string>hehe;
	string ch1,ch2,str;
	cin>>ch1;
	while(cin>>ch1&&ch1!="END")  
    {  
        cin>>ch2;
        hehe[ch2]=ch1;
		//cout<<hehe[ch2]<<"\n";
    }
	getline(cin, ch1);
	getline(cin, ch1);
	while(getline(cin,str)&&str!="END") 
    {  
		//cout<<str<<"\n";
		string temp;
		for(int i=0;i<str.size();i++)
		{
			if(str[i]>='a'&&str[i]<='z') 
				temp+=str[i];
			else
			{
				if(hehe[temp]!="")
					cout<<hehe[temp];
				else
					cout<<temp;
				cout<<str[i];
				temp.clear();
			}
		}
		printf("\n");
    }  
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值