线段树 简单实现

线段树

#include <iostream>
using namespace std;

const int maxN = 10000;

// 建树的过程, 根据arr 填充 tree
// start end 表示 node结点的范围, 每个结点是[start,end]的和
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值