#include<iostream>
const int MAX_LEN = 1000;
void build_tree(int arr[], int tree[], int node, int start, int end) {
if (start == end) {
tree[node] = arr[start];
}
else {
int mid = (start + end) / 2;
int left_node = 2 * node + 1;
int right_node = 2 * node + 2;
build_tree(arr, tree, left_node, start, mid);
build_tree(arr, tree, right_node, mid+1, end);
tree[node] = tree[left_node] + tree[right_node];
}
}
void upadate_tree(int arr[], int tree[], int node, int start, int end,int index,int value) {
if (start == end) {
arr[index] = value;
tree[node] = value;
}
else {
int mid = (start + end) / 2;
int left_node = 2 * node + 1;
int right_node = 2 * node + 2;
if (index >= start && index <= mid) {
upadate_tree(arr, tree, left_node, start, mid, index, value);
}
else {
upadate_tree(arr, tree, right_node, mid + 1, end, index, value);
}
tree[node] = tree[left_node] + tree[right_node];
}
}
int query_tree(int arr[], int tree[], int node, int start, int end, int left, int right) {
if (right<start||left>end) {
return 0;
}
else if (left<=start&&end<=right) {
return tree[node];
}
else if (start==end) {
std::cout << tree[node] << std::endl;
return tree[node];
}
else {
int mid = (start + end) / 2;
int left_node = 2 * node + 1;
int right_node = 2 * node + 2;
int sum_left = query_tree(arr, tree, left_node, start, mid, left, right);
int sum_right = query_tree(arr, tree, right_node, mid + 1, end, left, right);
return sum_left + sum_right;
}
}
int main() {
int arr[] = { 1,3,5,7,9,11 };
int size = 6;
int tree[MAX_LEN] = { 0 };
build_tree(arr, tree, 0, 0, size-1);
for (int i = 0; i < 15; i++) {
std::cout << "tree[" << i << "]=" << tree[i] << std::endl;
}
upadate_tree(arr, tree, 0, 0, size - 1, 4, 6);
std::cout << std::endl;
for (int i = 0; i < 15; i++) {
std::cout << "tree[" << i << "]=" << tree[i] << std::endl;
}
std::cout << query_tree(arr, tree, 0, 0, size - 1, 3, 5);
return 0;
}