您的位置:首页 > 其它

hdu 1075 字典树 和 map做法

2014-03-26 15:58 423 查看
开始写的时候

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: