数据结构-线段树 单点修改,区间查询

线段树构造:

在这里插入图片描述

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {
    //线段树 :单点修改,区间查询
    //用数组存储线段树
    static class Node{
        int l;
        int r;
        int sum;

        public Node(int l, int r, int sum) {
            this.l = l;
            this.r = r;
            this.sum = sum;
        }
    }
    static int N = 100010;
    static int [] w = new int[N];
    static Node [] tr = new Node[4*N];
    //线段树四个函数
    //1.初始化操作 u当前节点 l,r 左右区间
    public static void build(int u,int l,int r){
        if(l==r) tr[u] = new Node(l,l,w[l]);
        else{
            tr[u] = new Node(l,r,0);
            int mid = l + r >> 1;
            build(u<<1,l,mid);
            build(u<<1|1,mid+1,r);
            pushup(u);
        }
    }
    //2.pushup子节点向当前节点u传递信息
    public static void pushup(int u){
        tr[u].sum = tr[u<<1].sum + tr[u<<1|1].sum;
    }
    //3.单点修改 u,查找的当前节点,pos修改的位置,v修改的值
    public static void modify(int u,int pos,int v){
        if(tr[u].l==tr[u].r&&tr[u].l==pos){tr[u].sum += v;}
        else{
            int mid = tr[u].l+tr[u].r >>1;
            if(pos<=mid) modify(u<<1,pos,v);
            else modify(u<<1|1,pos,v);
            pushup(u);
        }
    }
    //4.区间查询 u表示遍历的当前节点,l左区间,r右区间
    public static int query(int u,int l, int r){
        //如果区间被包含在里
        if(tr[u].l>=l&&tr[u].r<=r) return tr[u].sum;
        else{
            int mid = tr[u].l + tr[u].r >> 1;
            int sum = 0;
            if(l<=mid) sum += query(u<<1,l,r);
            if(r>mid)  sum += query(u<<1|1,l,r);
            return sum ;
        }
    }

    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    public static void main(String[] args) throws IOException {
        String[] s = in.readLine().split(" ");
        int n = Integer.valueOf(s[0]);
        int m = Integer.valueOf(s[1]);
        String[] s1 = in.readLine().split(" ");
        //初始化数组
        for(int i=1;i<=n;i++) w[i] = Integer.valueOf(s1[i-1]);
        build(1,1,n);
        while(m-->0){
            String[] s2 = in.readLine().split(" ");
            int k = Integer.valueOf(s2[0]);
            int a = Integer.valueOf(s2[1]);
            int b = Integer.valueOf(s2[2]);
            if(k==0){
                System.out.println(query(1,a,b));
            }else {
                modify(1,a,b);
            }
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值