两种Trie写法

以luoguP2580为例

指针版

用时621ms, 内存59.3MB, 无\(O_2\)优化

#include<bits/stdc++.h>
using namespace std;

struct node{
    node *ch[26];
    int cnt;
} *root;

node* build() {
    node *k = new(node);
    k->cnt = 0;
    memset(k->ch, 0, sizeof k->ch);
    return k;
}

void insert(node* u, char *str) {
    for(int i = 0; str[i]; ++i) {
        if(u->ch[str[i] - 'a'] == NULL) u->ch[str[i] - 'a'] = build();
        u = u->ch[str[i] - 'a'];
    }
    u->cnt = 1;
    return;
}

int find(node* u, char *str) {
    for(int i = 0; str[i]; ++i) {
        if(u->ch[str[i] - 'a'] == NULL) return 0;
        u = u->ch[str[i] - 'a'];
    }
    return u->cnt;
}

void del(node* u, char *str) {
    for(int i = 0; str[i]; ++i) {
        u = u->ch[str[i] - 'a'];
    }
    u->cnt = -1;
    return;
}

int n, m;
char s[61];

int main() {
    
    root = build();
    
    scanf("%d", &n);
    for(int i = 1; i <= n; ++i) {
        scanf("%s", s);
        insert(root, s);
    }
    
    scanf("%d", &m);
    for(int i = 1; i <= m; ++i) {
        scanf("%s", s);
        int flag = find(root, s);
        if(!flag) cout << "WRONG\n";
        else {
            if(flag == -1) cout << "REPEAT\n";
            else {
                cout << "OK\n";
                del(root, s);
            }
        }
    }
    
    return 0;
}

数组动态内存板

用时589ms, 内存34.68MB, 无\(O_2\)优化

#include<bits/stdc++.h>
using namespace std;

const int maxn = 500001;
const int maxc = 26;

struct Trie{
    int *ch[maxn];
    int cnt[maxn];
    int tot;

    void init() {
        tot = 0;
        memset(ch, 0, sizeof ch);
        memset(cnt, 0, sizeof cnt);
    }

    void insert(char *str) {
        int p = 0;
        for(int i = 0; str[i]; ++i) {
            if(ch[p] == NULL) {
                ch[p] = new int[maxc];
                memset(ch[p], -1, sizeof(int) * maxc);
            }
            if(ch[p][str[i] - 'a'] == -1) ch[p][str[i] - 'a'] = ++tot;
            p = ch[p][str[i] - 'a'];
        }
        cnt[p]++;
    }

    int find(char *str) {
        int p = 0;
        for(int i = 0; str[i]; ++i) {
            if(ch[p][str[i] - 'a'] == -1) return 0;
            p = ch[p][str[i] - 'a'];
        }
        return cnt[p];
    }

    void del(char *str) {
        int p = 0;
        for(int i = 0; str[i]; ++i) {
            p = ch[p][str[i] - 'a'];
        }
        cnt[p] = -1;
    }
}trie;

int n, m;
char s[61];

int main() {
    trie.init();

    cin >> n;
    for(int i = 1; i <= n; ++i) {
        scanf("%s", s);
        trie.insert(s);
    }

    cin >> m;
    for(int i = 1; i <= m; ++i) {
        scanf("%s", s);
        if(!trie.find(s)) cout << "WRONG\n";
        else {
            if(trie.find(s) == -1) cout << "REPEAT\n";
            else {
                cout << "OK\n";
                trie.del(s);
            }
        }
    }

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/tztqwq/p/11087771.html