字典树

字典树_第1张图片

#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;


const int kind=26;

struct Treenode{
        int count;
        Treenode *next[kind];
        Treenode()
        {
                count=1;
                for(int i=0;i<kind;i++)
                {
                        next[i]=NULL;
                }
        }
};


void insert(Treenode *&root,char *word)
{
        Treenode *cur=root;
        int i=0,index=0;
        
        if(cur==NULL){
                cur = new Treenode();
                root = cur;
        }
        
        while(word[i])
        {
                index=word[i]-'a';
                if(cur->next[index]){
                        cur->next[index]->count++;
                }
                else{
                        cur->next[index]=new Treenode;
                }
                i++;
                cur = cur->next[index];
        }
}

int search(Treenode *root,char *word)
{
        Treenode *cur=root;
        int i=0,index=0;
        int ans;
        
        if(cur==NULL){
               return 0;
        }
        
        while(word[i])
        {
                index=word[i]-'a';
                if(!cur->next[index])
                {
                        return 0;
                }
                i++;
                cur=cur->next[index];
                ans=cur->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;
        }       

        return 0;
}


你可能感兴趣的:(struct,null,search,insert)