你们说,这题主席树能过吗?
查看原帖
你们说,这题主席树能过吗?
537934
litjohn楼主2024/12/28 17:04

空间被卡了。

#include <bits/stdc++.h>

using namespace std;
int n, m;
array<int, 2000005> a;

class president_tree {
private:
//public:
    static constexpr int min_limit = 1, max_limit = 2e6;

    struct node {
        int cnt;
        node *left, *right;

        node() : cnt(1), left(nullptr), right(nullptr) {};
    };

    vector<node *> roots = {nullptr};

    void modify(const int l, const int r, const int x, node *&p) {
        if (!p) {
            p = new node();
        } else {
            const node tmp = *p;
            p = new node();
            p->cnt += tmp.cnt;
            p->left = tmp.left;
            p->right = tmp.right;
        }

        if (l != r) {
            const int mid = (l + r) >> 1;
            if (x <= mid) {
                modify(l, mid, x, p->left);
            } else {
                modify(mid + 1, r, x, p->right);
            }
        }
    }

    int query(const int l, const int r, const int x, const node *p) {
        if (!p) {
            return 0;
        } else if (l == r) {
            return p->cnt;
        } else {
            const int mid = (l + r) >> 1;
            if (x <= mid) {
                return query(l, mid, x, p->left);
            } else {
                const int num = (p->left ? p->left->cnt : 0);

                return query(mid + 1, r, x, p->right) + num;
            }
        }
    }

public:
    void build(const int size, const auto &arr) {
        for (int i = 1; i <= size; ++i) {
            roots.push_back(roots.back());
            modify(min_limit, max_limit, arr[i], roots.back());
        }
    }

    inline int query(const int l, const int r, const int x) {
        int tmp1 = query(min_limit, max_limit, x, roots[r]), tmp2 = query(min_limit, max_limit, x, roots[l - 1]);

        return tmp1 - tmp2;
    }

    /*void print(int l, int r, const node *p) {
        if (p) {
            cerr << "l: " << l << " r: " << r << " cnt: " << p->cnt << "\n";

            int mid = (l + r) >> 1;
            print(l, mid, p->left);
            print(mid + 1, r, p->right);
        }
    }*/
} tree;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> n >> m;
    for (int i = 1; i <= n; ++i) {
        cin >> a[i];
    }

    tree.build(n, a);

    /*for (int i = 0; i < n; ++i) {
        tree.print(president_tree::min_limit, president_tree::max_limit, tree.roots[i]);
        cerr << "\n\n\n";
    }*/

    for (int _ = 0; _ < m; ++_) {
        int l, r, x;
        cin >> l >> r >> x;
        cout << tree.query(l, r, x) << "\n";
    }
    return 0;
}
2024/12/28 17:04
加载中...