trie树(字典树)学习笔记

trie树(字典树)

例题于是他错误的点名开始了

#include <cstdio>
#include <algorithm>
#include <cstring>

using namespace std;

struct node
{
    bool wrd, vis;
    int ch[26];
}trie[500009]; 
int siz = 1;

inline void insert(char* str)
{
    int t = 1, len = strlen(str);
    for(int i = 0; i < len; i++)
    {
        if(!trie[t].ch[str[i] - 'a'])
            t = trie[t].ch[str[i] - 'a'] = ++siz;
        else
            t = trie[t].ch[str[i] - 'a'];
    }
    trie[t].wrd = true;
}

inline int search(char* str)
{
    int t = 1, len = strlen(str);
    for(int i = 0; i < len; i++)
    {
        if(!trie[t].ch[str[i] - 'a'])
            return 0;
        else 
            t = trie[t].ch[str[i] - 'a'];
    }
    if(trie[t].wrd)
    {
        if(trie[t].vis) return -1;
        trie[t].vis = true;
        return 1;
    }
    else return 0;
}

int n, m;
char str[55];

int main() {
    scanf("%d", &n);
    for(int i = 1; i <= n; i++)
    {
        scanf("%s", str);
        insert(str);
    }
    scanf("%d", &m);
    for(int i = 0; i < m; i++)
    {
        scanf("%s", str);
        int res = search(str);
        if(res == 1) printf("OK\n");
        else if(res == -1) printf("REPEAT\n");
        else printf("WRONG\n");
    }
    return 0;
} 

8.7留坑待填

猜你喜欢

转载自www.cnblogs.com/wyswyz/p/11312816.html