2018.10.5 Trie封装(第一次写Trie树)

**

2018.10.5

**
今天比赛打炸,想了一个不太正确的做法,然后hash不会写,试着去写Trie数,还作死地试着写成数据结构,结构写了一个上午
代码如下:(这是没有封装的)

#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
const int N = 100007;
bool brk[32];
struct trie{
    struct tedge{
        bool a;
        tedge *nxt, *to;
        tedge(){
            nxt = to = NULL;
        }
    };
    int cnt;
    tedge *hd;
    tedge *fst[32];
    trie(){
        cnt = 0;
        hd = NULL;
        for(int i=0; i<32; ++i) fst[i] = NULL;
    }
    tedge *getnew(){
        tedge *a = new tedge;
        return a;
    }
} thet;

void broke(int x,bool *w){
    for(int i=0; i<32; ++i){
        w[i] = x & 1;
        x >>= 1;
    }
}
void add(int val,int dpth,trie *x,trie::tedge *itr){
    trie::tedge *itr2;
    itr2 = (*x).getnew();
    (*x).fst[dpth] = itr2;
    (*itr).to = itr2;
    (*itr2).a = val;
}
bool find(int x,void func(int,int,trie*,trie::tedge*)=NULL){
    broke(x,brk);
    int i, j;
    bool *k;
    trie::tedge *itr = thet.hd;
// tnode itr;
    for( i=31; i>=0; --i){
        itr = (*itr).to;
        if( itr == NULL ){
            if( func==NULL ) return false;
            (*func)(brk[i],i,&thet,itr);
        }
        else{
            k = & (*((*itr).to)).a;
            if( *k != brk[i] ){
                itr = (*itr).nxt;
                if( itr == NULL ) {
                    if( func==NULL ) return false;
                    (*func)(brk[i],i,&thet,itr);
                }
            }
            itr = (*itr).to;
        }
    }
    return true;
}
int main(){
    int n, a[N];
    int i, j;
    scanf("%d", &n);
    for( i=1; i<=n; ++i){
        scanf("%d", a+i);
        find(a[i],add);
    }              
    return 0;
}
    原文作者:Trie树
    原文地址: https://blog.csdn.net/qq_42944198/article/details/82943325
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞