线段树

11  •  3个月前


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// 初始化线段树节点
struct SegmentTree {
    vector<int> tree;
    int n;

    SegmentTree(int size) {
        n = size;
        tree.resize(4 * n);
    }

    // 构建线段树
    void build(vector<int>& heights, int v, int tl, int tr) {
        if (tl == tr) {
            tree[v] = heights[tl];
        } else {
            int tm = (tl + tr) / 2;
            build(heights, v * 2, tl, tm);
            build(heights, v * 2 + 1, tm + 1, tr);
            tree[v] = max(tree[v * 2], tree[v * 2 + 1]);
        }
    }

    // 区间最大值查询
    int query(int v, int tl, int tr, int l, int r) {
        if (l > r) {
            return -1; // 如果区间无效,返回一个无效值
        }
        if (l == tl && r == tr) {
            return tree[v];
        }
        int tm = (tl + tr) / 2;
        return max(query(v * 2, tl, tm, l, min(r, tm)),
                   query(v * 2 + 1, tm + 1, tr, max(l, tm + 1), r));
    }

    // 更新某个位置的高度值
    void update(int v, int tl, int tr, int pos, int new_val) {
        if (tl == tr) {
            tree[v] = new_val;
        } else {
            int tm = (tl + tr) / 2;
            if (pos <= tm) {
                update(v * 2, tl, tm, pos, new_val);
            } else {
                update(v * 2 + 1, tm + 1, tr, pos, new_val);
            }
            tree[v] = max(tree[v * 2], tree[v * 2 + 1]);
        }
    }
};

int main() {
    int apple_heights[10];
    int max_reach_height;
    int bench_height = 30;

    // 读取10个苹果的高度
    for (int i = 0; i < 10; ++i) {
        cin >> apple_heights[i];
    }

    // 读取陶陶的最大伸手高度
    cin >> max_reach_height;

    // 计算陶陶站在板凳上后的最大可达高度
    int max_height_with_bench = max_reach_height + bench_height;

    // 构建线段树
    SegmentTree segTree(10);
    vector<int> heights(apple_heights, apple_heights + 10);
    segTree.build(heights, 1, 0, 9);

    // 计算能够摘到的苹果数量
    int reachable_count = 0;
    for (int i = 0; i < 10; ++i) {
        if (segTree.query(1, 0, 9, i, i) <= max_height_with_bench) {
            reachable_count++;
        }
    }

    // 输出结果
    cout << reachable_count << endl;

    return 0;
}


评论:

good job!


天生我材必有难,千金散尽还债来  •  3个月前

请先登录,才能进行评论