线段树
#include <iostream>
using namespace std;
const int maxN = 10000;
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 - start) / 2;
int left_node = node * 2 + 1;
int right_node = node * 2 + 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 update_tree(int arr[], int tree[], int node, int start, int end, int ind, int target)
{
if (start == end)
{
tree[node] = target;
arr[start] = target;
}
else
{
int mid = start + (end - start) / 2;
int left_node = node * 2 + 1;
int right_node = node * 2 + 2;
if (ind >= start && ind <= mid)
{
update_tree(arr, tree, left_node, start, mid, ind, target);
}
else if (ind > mid && ind <= end)
{
update_tree(arr, tree, right_node, mid+1, end, ind, target);
}
tree[node] = tree[right_node] + tree[left_node];
}
}
int query_tree(int arr[], int tree[], int node, int start, int end, int L, int R)
{
if (R < start || L > end)
return 0;
else if (start == end)
return tree[node];
else if (L <= start && R >= end)
return tree[node];
int mid = start + (end - start) / 2;
int left_node = node * 2 + 1;
int right_node = node * 2 + 2;
int left_tree = query_tree(arr, tree, left_node, start, mid, L, R);
int right_tree = query_tree(arr, tree, right_node, mid+1, end, L, R);
return left_tree + right_tree;
}
int main(int argc, const char * argv[]) {
int arr[] = {1,3,5,7,9,11};
int size = 6;
int tree[maxN] = {0};
build_tree(arr, tree, 0, 0, size-1);
for(int i = 0; i < 15; i++)
{
cout<<tree[i]<<endl;
}
cout<<endl;
update_tree(arr, tree, 0, 0, size-1, 4, 6);
for(int i = 0; i < 15; i++)
{
cout<<tree[i]<<endl;
}
cout<<endl;
cout<<query_tree(arr, tree, 0, 0, size-1, 2, 5)<<endl;
return 0;
}