您的位置:首页 > 其它

HDU-1075 tire

2013-07-26 10:56 176 查看
题目连接

这题很有意思。

分析一下我的解题思路:先把字符串插入到字典树中,在最后一个字符中开辟一个空间,来存放与它相对应的字符串,这样就可以处理:有公共前缀的字符了和字符长短不一的情况,所以这样操作很方便了。

代码分析见注释:(思路很简单),此题有很多指针操作,看不懂的,先把指针学好哦!

#include<cstdio>
#include<cstring>
#include<cctype>
struct tire{
char *ch;
tire *next[26];
tire(){
ch=NULL;
memset(next,0,sizeof(next));
}
};
tire *root=new tire;

inline void built(char *s,char*t)
{
tire *tmp=root;
int i=0,pos;
while(t[i]){
pos=t[i]-'a';
if(tmp->next[pos]==0) tmp->next[pos]=new tire;
tmp=tmp->next[pos];
i++;
}
tmp->ch=new char[15];   //tmp指针此时一定指的位置是最后一个字符了,按着我的思路,就分配内存了。
strcpy(tmp->ch,s);
}

inline void search(char *s)
{
tire *tmp=root;
char t[11];
int i=0,j=0,goal,flag=0;
while(s[i]){
goal=s[i]-'a';
if(tmp->next[goal]==0){
flag=1;
break;
}
tmp=tmp->next[goal];
i++;
}
if(flag) printf("%s",s);    //如果是没有该字符串就直接输出
else if(tmp->ch==0) printf("%s",s); //处理公共前缀的(指针此时指的位置是前面的,所以没分配内存)。
else {
strcpy(t,tmp->ch);
printf("%s",t);
}
}

int read(char *t,char *p)
{
int i;
for(i=0;;i++){
if(isalpha(*(p+i))){  //判断是否是字母
*(t+i)=*(p+i);   //复制。
}
else break;
}
*(t+i)='\0';  //千万别忘了这个,这是printf输出的结束的标识。
return i;   //返回字符串的长度。
}

int main()
{
char s[15],t[15];
char book[4000];
while(scanf("%s",s),s[0]!='E'){
if(s[0]=='S') continue;
scanf("%s",t);
built(s,t);
}
scanf("%s",s);
getchar();   //这个需要,处理跳行的 。
while(gets(book),strcmp(book,"END")!=0){
char *p=book;
while(*p){
p+=read(t,p);
search(t);
while(!isalpha(*p)){
if(*p==0) break;
printf("%c",*p);
p++;
}
}
printf("\n");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  tire