- 1. 区域和检索 - 数组可修改--线段树
题目地址
写了个线段树的轮子:线段树数据结构,数组seg_tree,构造函数build_tree,单点修改函数update_tree,区间查询函数query_tree。
b站线段树讲解+手撕代码
class NumArray {
vector<int> nums;
public:
NumArray(vector<int>& nums) {
this->nums=nums;
seg_tree.resize(pow(2, (int)ceil(log2(nums.size())) + 1));
build_tree(0, 0, nums.size() - 1);
}
void update(int index, int val) {
update_tree(0, 0, nums.size() - 1, index, val);
}
int sumRange(int left, int right) {
return query_tree(0, 0, nums.size() - 1, left, right);
}
private:
vector<int> seg_tree;//线段树
//变量名中有node的都是线段树的元素,否则是nums数组中的元素
void build_tree(int node, int start, int end){//建树
if(start == end){
seg_tree[node] = nums[start];
return;
}
int mid = (start + end) / 2;
int left_node = node * 2 + 1;
int right_node = node * 2 + 2;
build_tree(left_node, start, mid);
build_tree(right_node, mid + 1, end);
seg_tree[node] = seg_tree[left_node] + seg_tree[right_node];
}
void update_tree(int node, int start, int end, int index, int val){//更新线段树
if(start == end){
nums[index] = val;
seg_tree[node] = val;
return;
}
int mid = (start + end) / 2;
int left_node = node * 2 + 1;
int right_node = node * 2 + 2;
if(index <= mid)
update_tree(left_node, start, mid, index, val);
else
update_tree(right_node, mid + 1, end, index, val);
seg_tree[node] = seg_tree[left_node] + seg_tree[right_node];
}
int query_tree(int node, int start, int end, int left, int right){//查询区间和
if(start > right || end < left){
return 0;
}
else if(start >= left && end <= right){
return seg_tree[node];
}
int mid = (start + end) / 2;
int left_node = node * 2 + 1;
int right_node = node * 2 + 2;
int left_sum = query_tree(left_node, start, mid, left, right);
int right_sum = query_tree(right_node, mid+1, end, left, right);
return left_sum + right_sum;
}
};
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)