问题描述
我正在尝试处理一个问题陈述,其中指出: 给定一个整数数组和一系列索引 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 (将#修改为@)