生成一份线段树的c++代码
时间: 2023-11-14 14:42:21 浏览: 98
下面是一个简单的线段树(Segment Tree)的C++代码示例:
```cpp
#include <iostream>
#include <vector>
using namespace std;
// 线段树节点
struct SegmentTreeNode {
int start, end;
int sum;
SegmentTreeNode* left;
SegmentTreeNode* right;
SegmentTreeNode(int start, int end) {
this->start = start;
this->end = end;
this->sum = 0;
this->left = nullptr;
this->right = nullptr;
}
};
// 构建线段树
SegmentTreeNode* buildSegmentTree(vector<int>& nums, int start, int end) {
if (start > end)
return nullptr;
SegmentTreeNode* root = new SegmentTreeNode(start, end);
if (start == end) {
root->sum = nums[start];
return root;
}
int mid = start + (end - start) / 2;
root->left = buildSegmentTree(nums, start, mid);
root->right = buildSegmentTree(nums, mid + 1, end);
root->sum = root->left->sum + root->right->sum;
return root;
}
// 查询区间和
int querySum(SegmentTreeNode* root, int start, int end) {
if (root == nullptr || start > root->end || end < root->start)
return 0;
if (start <= root->start && end >= root->end)
return root->sum;
return querySum(root->left, start, end) + querySum(root->right, start, end);
}
// 更新指定位置的元素值
void update(SegmentTreeNode* root, int index, int value) {
if (root == nullptr || index < root->start || index > root->end)
return;
if (root->start == root->end) {
root->sum = value;
return;
}
update(root->left, index, value);
update(root->right, index, value);
root->sum = root->left->sum + root->right->sum;
}
int main() {
vector<int> nums = {1, 3, 5, 7, 9, 11};
int n = nums.size();
SegmentTreeNode* root = buildSegmentTree(nums, 0, n - 1);
int sum1 = querySum(root, 1, 4);
cout << "区间和为:" << sum1 << endl;
update(root, 2, 6);
int sum2 = querySum(root, 1, 4);
cout << "更新后的区间和为:" << sum2 << endl;
return 0;
}
```
这段代码实现了一个简单的线段树,包括构建线段树、查询区间和以及更新指定位置的元素值的功能。
在主函数中,我们首先构建了一个线段树,并使用`querySum`函数查询了区间[1, 4]的和。然后,我们使用`update`函数更新了索引为2的元素值为6,并再次查询了区间[1, 4]的和。
你可以根据需要修改`nums`数组中的元素值和查询的区间范围进行不同的测试。
阅读全文