HDU1251 字典树
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251
这道题的意思就是给你一定的单词数目,然后再给你单词前缀,求出这个单词前缀的单词数目,这道题看别人的代码敲出来了,由于一个指针的问题困扰了很久,定义一个新指针要给他分配一个空间,用new。
#include<iostream> #include<cstdlib> #include<cstring> using namespace std; typedef struct trie{ int v; trie *next[26]; }; trie *root; void build(char *s1){ trie *q=root,*p; int i,j,k,str; str=strlen(s1); for(i=0;i<str;i++){ j=s1[i]-'a'; if(q->next[j]==NULL){ p=(trie*)malloc(sizeof(trie)); p->v=1; for(k=0;k<26;k++){ p->next[k]=NULL; } q->next[j]=p; q=q->next[j]; } else{ q->next[j]->v++; q=q->next[j]; } } } int find(char *s1){ int i,j,str; trie *q=root; str=strlen(s1); for(i=0;i<str;i++){ j=s1[i]-'a'; q=q->next[j]; if(q==NULL){ return 0; } } return q->v; } int main() { int i,ans; char s1[20]; root=new trie; for(i=0;i<26;i++){ root->next[i]=NULL; } while(gets(s1)&&s1[0]!='\0'){ build(s1); } while(gets(s1)){ ans=find(s1); cout<<ans<<endl; } delete root; return 0; }
这题就是直观的查字典,给你一个单词对应的词组,然后再给你词组让你找到这个单词,这题卡在一个next后面一层节点没有更新,问了别人才知道的,牢记!!!
#include<iostream> #include<cstring> #include<cstdlib> using namespace std; char ans[15]; typedef struct trie{ trie *next[27]; char v[15]; }; trie *root; void creat(char *s1,char *s2){ int str,i,j; str=strlen(s1); trie *q=root; for(i=0;i<str;i++){ j=s1[i]-'a'; // cout<<j<<' '<<q->next[j]<<' '; // if(q->next[j]==NULL){ // cout<<"y"; // } if(q->next[j]==NULL){ q->next[j]=new trie; memset(q->v,0,sizeof(q->v)); for(int k=0;k<26;k++) q->next[j]->next[k]=0; } q=q->next[j]; } strcpy(q->v,s2); //cout<<q->v<<endl; } int find(char *s1){ int str,i,j; trie *q=root; str=strlen(s1); for(i=0;i<str;i++){ j=s1[i]-'a'; if(q->next[j]==NULL){ strcpy(ans,"eh"); return 0; } q=q->next[j]; } strcpy(ans,q->v); return 0; } int main() { int i; char s[30],s1[15],s2[15]; root=new trie; for(i=0;i<26;i++){ root->next[i]=NULL; } while(gets(s)&&s[0]!='\0'){ sscanf(s,"%s %s",s2,s1); creat(s1,s2); } while(scanf("%s",s1)!=EOF){ find(s1); cout<<ans<<endl; } return 0; }