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"); } }
相关文章推荐
- HDU 1075 What Are You Talking About
- HDU 1075 What Are You Talking About (Trie)
- HDU 1075 字典树 树搜索 逆路径输出单词
- hdu-1075 What Are You Talking About
- hdu 1075 字典树 和 map做法
- 字典树详解(附题:HDU 1075 What are you talking about)
- hdu 1075 What Are You Talking About
- hdu 1075 What Are You Talking About(map)
- hdu 1075 What Are You Talking About (字典树·文字翻译)
- hdu 1075 What Are You Talking About(字典树)
- 字典树(入门) 之 hdu 1075
- HDU 1075 What Are You Talking About Trie题解
- hdu&nbsp;1075&nbsp;what&nbsp;are&nbsp;you&nbsp;talking&nbsp;ab…
- hdu 1075 tire树
- hdu 1075 翻译火星文 trie树 / map
- HDU 1075 What Are You Talking About
- HDU - 6191 Query on A Tree 可持久化Tire
- hdu 1075 What Are You Talking About map
- HDU 1075 What Are You Talking About
- hdu 1075 What Are You Talking About(map)