您的位置:首页 > 其它

hdu 1075(字典树)

2013-04-05 16:36 218 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1075

wa了好多次啊。。。心都碎了。。。然后不知道怎么一改就对了。。。orz...

建树的的时候每个单词的的最后一个结点应该加入译文的信息。。。

islower()用于判断小写字母很好用。。。

View Code

#include<iostream>
#include<string>
#include<cstring>
using namespace std;
struct Tire{
char s[14];
Tire *next[26];
};
Tire *root;

void CreateTire(char str[],char ss[]){
int len=strlen(ss);
Tire *p=root,*q;
for(int i=0;i<len;i++){
int id=ss[i]-'a';
if(p->next[id]==NULL){
q=(Tire *)malloc(sizeof(Tire));
for(int i=0;i<26;i++){
q->next[i]=NULL;
}
strcpy(q->s,"");
p->next[id]=q;
p=p->next[id];
}else {
p=p->next[id];
}
}
strcpy(p->s,str);
}

Tire *FindTire(string &ss){
Tire *p=root;
for(int i=0;i<ss.size();i++){
int id=ss[i]-'a';
if(p->next[id]==NULL)return NULL;
p=p->next[id];
}
if(strcmp(p->s,""))return p;
return NULL;
}

int main(){
char str[3300];
root=(Tire *)malloc(sizeof(Tire));
for(int i=0;i<26;i++){
root->next[i]=NULL;
}
strcpy(root->s,"");
while(~scanf("%s",str)){
if(str[0]=='S')continue;
if(str[0]=='E')break;
char ss[14];
scanf("%s",ss);
CreateTire(str,ss);
}
getchar();
while(gets(str)){
if(str[0]=='S')continue;
if(str[0]=='E')break;
int len=strlen(str);
string s;
for(int i=0;i<len;i++){
s="";
if(islower(str[i])){
int k=i;
while(k<len&&islower(str[k])){
s+=str[k];
k++;
}
Tire *p=FindTire(s);
if(p!=NULL){
printf("%s",p->s);
}else {
for(int j=i;j<k;j++){
printf("%c",str[j]);
}
}
i=k-1;
}else
printf("%c",str[i]);
}
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: