Node:Trie数(字典树)

来源:互联网 发布:淘宝的我是卖家在哪里 编辑:程序博客网 时间:2024/04/30 02:53

为了看一看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;}


0 0
原创粉丝点击