编程语言
首页 > 编程语言> > 磊磊零基础打卡算法:day16 c++ Trie树

磊磊零基础打卡算法:day16 c++ Trie树

作者:互联网

5.19

Trie树:

例题:https://www.acwing.com/problem/content/837/


#include "iostream"
using namespace std;
const int N = 100010;
int son[N][26], cnt[N], idx;
void insert(char str[]) {
    int p;
    for (int i = 0; i < str[i]; i++) {
        int u = str[i] - 'a';
        if (!son[p][u])
            son[p][u] = ++idx;
        p = son[p][u];
    }
    cnt[p]++;
}
int query(char str[]) {
    int p;
    for (int i = 0; i < str[i]; i++) {
        int u = str[i] - 'a';
        if (!son[p][u])
            return 0;
        p = son[p][u];
    }
    return cnt[p];
}
int main() {
    int m;
    cin >> m;
    char str[N];
    while (m--) {
        char s;
        cin >> s;
        if (s == 'I') {
            cin >> str;
            insert(str);
        } else if (s == 'Q') {
            cin >> str;
            cout << query(str) << endl;
        }
    }
    return 0;
}

解释图片:

 

 

图片来源:AcWing 835. Trie字符串统计 - AcWing

标签:cnt,磊磊,Trie,++,son,char,int,str,打卡
来源: https://www.cnblogs.com/gwl999/p/16290694.html