hdu1251在词典里统计前缀出现的个数

banana band bee absolute acm    ba b band abc

#include<iostream>
using namespace std;
//数据结构
struct Treenode{
       int count;
       Treenode *next[26];
       Treenode(){
                  count=1;
                  for(int i=0;i<26;i++)
                      next[i]=NULL;
       }
};
//插入建树
void insert(Treenode *&root,char *word){
     if(root==NULL)
         root=new Treenode();
     Treenode *location=root;
     int i=0,branch=0;
     while(word[i])
     {
         branch=word[i]-'a';
         if(location->next[branch])
             location->next[branch]->count++;
         else 
             location->next[branch]=new Treenode();
         i++;
         location=location->next[branch];
     }
}
//查找
int search(Treenode *root,char *word)
{
     if(root==NULL) return 0;
     Treenode *location=root;
     int branch=0,i=0,ans;
     while(word[i])
     {
          branch=word[i]-'a';
          if(!location->next[branch])
              return 0;
          i++;
          location=location->next[branch];
          ans=location->count;    
     }
     return ans;
}

int main()
{
    char word[10];
    char ask[10];
    Treenode *root=NULL;
    
    while(gets(word))
    {
        if(word[0]=='\0')  break;
        insert(root,word);
    }
    while(gets(ask))
    {
        cout<<search(root,ask)<<endl;
    }
    getchar();
    return 0;
}

 

posted @ 2013-09-19 15:02  一枚程序员  阅读(340)  评论(0编辑  收藏  举报