hdu 1251 字典树的水题

字典树的水题



#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
struct node {
  int num ;
  node *next[26];
} ;
node * root;
void trie(){
  int i,j;
  root = new node;
  root->num = 0;
  for(int i=0;i<=25;i++){
    root ->next[i] = NULL;
  }
}

void insert(char ss[]){
  node *p = root,*t;
  for(int i=0;ss[i];i++){
      int id = ss[i]-'a';
      if(!p->next[id]){
          t = new node;
      t->num = 0 ;
    for(int j=0;j<26;j++)
      t->next[j] = NULL;
    p->next[id] = t;
      }
      p=p->next[id];
      p->num  ++ ;
  }


}
int  search (char ss[]){
   node *p= root;
   for(int i=0 ;ss[i];i++){
      int t = ss[i] - 'a';
      if(p->next[t]){
         p = p->next[t];
      }else {
        return 0;
      }
   }
   return p->num ;
}
char s[20];
int main(){
  trie();
  while(gets(s))
    {
        if(strcmp(s,"")==0) break;
            insert(s);
    }
    while(scanf("%s",s)!=EOF)
        printf("%d\n",search(s));
    return 0;

}


你可能感兴趣的:(hdu 1251 字典树的水题)