Node:Trie数(字典树)

为了看一看AC自动机,先看看Trie树

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <stack>
#include <queue>

#define flush(arr,i) memset(arr,i,sizeof(arr))
using namespace std;
const int maxn=26;
int n;

/*
Trie树(字典树)
*/

struct TrieNode
{
    //标记结尾
    int flag;
    TrieNode *child[maxn];
    TrieNode()
    {
        flag = 0;
        flush(this->child, 0);
    }
};

TrieNode *root;

void insertNode(char *c)
{
    int len = strlen(c), i = 0, pos;
    TrieNode *p = root;
    while(i < len)
    {
        pos = c[i] - 'a';
        if(p->child[pos] == nullptr)
            p->child[pos] = new TrieNode();
        p = p->child[pos];
        i++;
    }
    p->flag = 1;
}

void buildTriTree()
{
    root = new TrieNode();
    scanf("%d", &n);
    char word[maxn];
    for(int i = 0; i < n; i++)
    {
        scanf("%s", word);
        insertNode(word);
        flush(word, 0);
    }
    printf("init finish...\n");

}

bool searchResult(char *key)
{
    int len = strlen(key), i = 0, pos;
    TrieNode *p = root;

    while(i < len)
    {
        pos = key[i] - 'a';

        if(p->child[pos] == nullptr)
            return false;
        else
            p = p->child[pos];

        i++;
    }
    if(p->flag)
        return true;
    return false;
}

int main()
{
    //freopen("data.txt","r",stdin);
    buildTriTree();
    char key[maxn];
    while(true)
    {
        scanf("%s", key);
        if(strcmp(key, "quit") == 0)
            break;
        searchResult(key) == true ? printf("exist\n") : printf("Not exist\n");
        flush(key, 0);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值