C++算法基础——线段树(Segment Tree)

C++算法基础——线段树(Segment Tree)_第1张图片

/*
node表示树状数组的下标
其他的表示数组的下标
*/
#include 
using  namespace std;
#define max_tree  1000
int tree[1000] = {0};
void build_tree(int arr[], int tree[], int node, int start, int end);  //建立一个树状
void update(int arr[], int tree[], int node, int start, int end,int idx,int val);//改变数组arr中的一个数,并更新树状数组
    int main(){
        int arr[] = {1, 2, 3, 4, 5, 6};
        build_tree(arr, tree, 0, 0, 5);
        
            for (int i = 0; i < 11; i++)
            {
                printf("tree[%d]=%d\n", i, tree[i]);
            }
		update(arr, tree, 0, 0, 5,3,2);
                puts("");
                for (int i = 0; i < 11; i++)
                {
                    printf("tree[%d]=%d\n", i, tree[i]);
                }
            return 0;
        }
void build_tree(int arr[], int tree[], int node, int start, int end){
    if(start==end)
    {
        tree[node] = arr[end];
    }
   else{
        int mid = (start + end) / 2;   //例如 :  将[0-5]分为 [0-2]和[3-5]
        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 update(int arr[], int tree[], int node, int start, int end, int idx,int val)
{
 if(start==end){
     arr[idx] = val;
     tree[node] = val;
 }
 else{
     int mid = (start + end) / 2; 
     int left_node = 2 * node + 1;
     int right_node = 2 * node + 2;
     if(idx>=start&&idx<=mid)
     update(arr, tree, left_node, start, mid, idx, val);
     else
     update(arr, tree, right_node,mid+1,end,idx, val);

     tree[node] = tree[left_node] + tree[right_node];
 }
 }


你可能感兴趣的:(c++,算法,算法,c++,数据结构)