poj-2503 字典树

来源:互联网 发布:unity3d 导弹跟随 编辑:程序博客网 时间:2024/04/30 20:38
#include <stdio.h>  #include <stdlib.h>  #include <string.h>  struct Node  {      char low[11];//存放最终的字符串       Node *next[26];//26个英文字母指针   };Node *root,*p,*q;  void Init(Node *root)//初始化   {      root->low[0]='#';//'#'表示没有存储字符串           for(int i=0;i<26;i++)          root->next[i]=NULL;  }  void BuildTire(char *s2,char *s1)  {      int i,v;      for(i=0,p=root;i<strlen(s2);i++)      {          v=s2[i]-'a';            if(p->next[v]==NULL)//v节点为空         {              q=(struct Node*)malloc(sizeof(Node));              Init(q);              p->next[v]=q;          }          p=p->next[v]; //p移动     }      strcpy(p->low,s1);  }  Node *Insearch(char *str)  {      int i,v;      for(i=0,p=root;i<strlen(str);i++)      {          v=str[i]-'a';          if(p->next[v]==NULL)              break;          p=p->next[v];      }      return p;  }  int main()  {      char str[23],s1[11],s2[11];      root=(struct Node *)malloc(sizeof(Node));      Init(root);      while(gets(str) && str[0]!='\0')      {          sscanf(str,"%s%s",s1,s2);          BuildTire(s2,s1);      }      while(gets(str) && str[0]!='\0')      {          Node *r=Insearch(str);          if(r->low[0]!='#')              printf("%s\n",p->low);          else              printf("eh\n");      }      return 0;  }  

0 0
原创粉丝点击