1. 程式人生 > >基本數據結構①——trie樹

基本數據結構①——trie樹

char 記錄 數據 have inf nbsp com pro 編號

RT

trie樹是一種用於實現字符串的快速檢索的樹結構;大該是每個節點都有若幹個指向字符的指針;如圖:

技術分享圖片

好像看不清,不過沒多大事;

然後trie樹支持兩個操作:插入,查找;

先放代碼

struct data      
        p=trie[p].son[ch];
    }
    trie[p].have=true;
}
int f(char *s)
{
    int len=strlen(s),p=0;
    for(int k=0;k<len;++k)
    {
        int ch=s[k]-a;
        if(!trie[p].son[ch]) return
false; p=trie[p].son[ch]; } if(!trie[p].have) return false;//其實寫return trie[p].have 就行; }

然後就可以來到例題https://www.luogu.org/problemnew/show/P2580;

但是這學了trie樹還需要一個樹上dfs

比如我們可以按字典序記錄;

void dfs(int p)
{
    if(trie[p].num) a[trie[p].num]=++t;    //當他是結尾時,標記,a數組存的是字符串編號
    for(int i=0;i<26;++i)
    {
        
if(trie[p].son[i]) dfs(trie[p].son[i]); } }

以後再補充;

基本數據結構①——trie樹