前缀树

[Algo] 前缀树

1. 静态数组实现前缀树

// 静态数组实现前缀树
int cnt = 0;
int tree[MAX + 1][26];
int pass[MAX + 1];
int End[MAX + 1];

void build()
{
    cnt = 1;
}

void clear()
{
    for (int i = 1; i <=cnt; i++)
    {
        for (int j = 0; j < 26; j++) tree[i][j] = 0;
        pass[i] = 0;
        End[i] = 0;
    }
}

void insert(const string &s)
{
    int cur = 1;
    pass[cur]++;
    for (const char &ch : s)
    {
        int index = ch - 'a';
        if (tree[cur][index] == 0) tree[cur][index] = ++cnt;
        cur = tree[cur][index];
        pass[cur]++;
    }
    End[cur]++;
}

int searchWord(const string &s)
{
    int cur = 1;
    for (const char &ch : s)
    {
        int index = ch - 'a';
        if (tree[cur][index] == 0) return 0;
        cur = tree[cur][index];
    }
    return End[cur];
}

int searchPrefix(const string &s)
{
    int cur = 1;
    for (const char &ch : s)
    {
        int index = ch - 'a';
        if (tree[cur][index] == 0) return 0;
        cur = tree[cur][index];
    }
    return pass[cur];
}

void erase(const string &s)
{
    if (searchWord(s) == 0) return;
    int cur = 1;
    pass[cur]--;
    for (const char &ch : s)
    {
        int index = ch - 'a';
        if (--pass[tree[cur][index]] == 0) { tree[cur][index] = 0; return; }
        cur = tree[cur][index];
    }
    End[cur]--;
}

2. 数组中两数的最大异或值

// 1. 数组中两数的最大异或值
// https://leetcode.cn/problems/maximum-xor-of-two-numbers-in-an-array/description/
int cnt = 0;
int tree[MAX + 1][2];

void insert(const int num)
{
    int cur = 1;
    for (int i = 31, status; i >= 0; i--)
    {
        status = (num >> i) & 1;
        int index = status;
        if (tree[cur][index] == 0) tree[cur][index] = ++cnt;
        cur = tree[cur][index];
    }
}

void build(const vector<int> &v)
{
    cnt = 1;
    for (const auto &e : v) insert(e);
}

int maxXor(const int num)
{
    int cur = 1;
    int ans = 0;
    for (int i = 31, status, want; i >= 0; i--)
    {
        status = (num >> i) & 1;
        want = status ^ 1;
        if (tree[cur][want] == 0) want = want ^ 1;
        ans |= (status ^ want) << i;
        cur = tree[cur][want];
    }
    return ans;
}

int arrMaxXor(const vector<int> &v)
{
    build(v);
    int ans = 0;
    for (auto e : v) ans = max(ans, maxXor(e));
    return ans;
}
posted @ 2024-12-20 15:14  yaoguyuan  阅读(14)  评论(0)    收藏  举报