微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

具有空间优化段树的范围最小查询

如何解决具有空间优化段树的范围最小查询

我正在尝试处理一个问题陈述,其中指出: 给定一个整数数组和一系列索引 l 和 r,找到存储该范围内最小元素的索引。如果有多个最小值,则返回最左边索引对应的那个。

这是一个标准的 RMQ 问题,可以使用各种数据来解决。 Fenwick 树、平方根分解、段树等结构。我知道,为段树实现递归方法是直接的。但是,该方法要求树具有 4N 个节点(其中 N 是原始数组中的元素数)。我最近遇到了一种空间优化的方法来构建一个只有 2N 个节点的线段树。但是,我实现的实用函数给出了错误输出,如果有人能指出我遗漏的内容,我们将不胜感激。

以下是代码片段:

void build_tree(vector<int>& nums) {
    // create a segment tree
    vector<int> tree(nums.size()*2);

    for (int i = nums.size(); i < tree.size(); ++i) {
        tree[i] = i-n; // For leaves,just store their index
    }

    // Fill the parent nodes
    for (int i = n-1; i >=0; --i) {
        int left = tree[i*2],right = tree[i*2+1];
            
        if (nums[left] <= nums[right]) {
            tree[i] = left;
        } else {
            tree[i] = right;
        }
    }
}


int query_min_index_in_range(vector<int>& tree,vector<int>& nums,int l,int r) {
        
   l += tree.size()/2,r += tree.size()/2; // Start from the leaves
   int ans = nums[tree[l]] <= nums[tree[r]]? tree[l]:tree[r];
   while (l<=r) {
       // Update the minimum so far
       if (nums[tree[r]] <= nums[ans]) {
           ans = tree[r];
        }
        if (nums[tree[l]] <= nums[ans]) {
            ans = tree[l];
        }
            
        if (l%2 == 1) L++; // If leftmost range
        if (r%2 == 0) r--; // If rightmost range
        l/=2,r/=2; // Move to parent
    }

    return ans;
}
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。