hdu 1251 统计难题 (trie树)

来源:互联网 发布:linux cgroups 编辑:程序博客网 时间:2024/05/16 17:31

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1251

不怎么写结构体,这回终于好好复习了下。


#include<stdio.h>  #include<string.h>  #include<stdlib.h>    typedef struct node{      /*typedef可以将struct node写为简单的trie,node*/      struct node*next[26];   /*指向下个node的指针*/      bool exist;      int count;  }*trie,node;    //*trie为指向自己的指针变量。虽然不知定义上node是何意,但貌似大家都这么写~~·  trie root;    void creat(trie &p){  /*定义p为结构指针,为结构体的首地址。(*&p=p)  */      p=(trie)malloc(sizeof(node));  /*p是trie类型的,如果不加(trie)则默认返回void类型的,所以要强制转化*/      for(int i=0;i<26;i++)          /*把26个指向孩子的指针赋为0*/          p->next[i]=0;      p->exist=false;      p->count=0;  }    void insert(trie p,char s[]){      int k=0 ;      while(s[k]!='\0'){          if(!p->next[s[k]-'a']){   /*插入时若下一个为空,则建个新的*/              trie q;              creat(q);              p->next[s[k]-'a']=q;  /*s[k]所代表字母指向新建的节点*/          }          p=p->next[s[k]-'a'];      /*指针向下移*/          k++;      }      p->count++;    p->exist=true;  }    int find(trie p,char s[]){      int k=0;      while(s[k]!='\0'&&p->next[s[k]-'a']){          p=p->next[s[k]-'a'];          k++;      }      if(s[k]=='\0')          return p->count;      else return 0;  }  int main(){      char str[11];      bool flag=false;      creat(root);    /*初始化根节点*/      while(gets(str)){          if(flag)              printf("%d\n",find(root,str));          else if(strlen(str)!=0){                  insert(root,str);               }               else{                  flag=true;               }      }      return 0;  }  




原创粉丝点击