首页 > 代码库 > 字典树模板

字典树模板

const int N=27;

struct node{
    int cnt;
    node* childs[N];
    node(){
        cnt=0;
        for(int i=0;i<N;i++)
            childs[i]=NULL;
    }
};

node *root=new node();
node *current,*newnode;

void insert(char *str){
    current=root;
    for(int i=0;i<strlen(str);i++){
        int m=str[i]-a;
        if(current->childs[m]!=NULL){
            current=current->childs[m];
            ++(current->cnt);
        }else{
            newnode=new node;
            ++(newnode->cnt);
            current->childs[m]=newnode;
            current=newnode;
        }
    }
}

int search(char *str){
    current=root;
    for(int i=0;i<strlen(str);i++){
        int m=str[i]-a;
        if(current->childs[m]==NULL)
            return 0;
        current=current->childs[m];
    }
    return current->cnt;
}

 

字典树模板