class 4 笔记

int sum(int v, int tl, int tr, int l, int r) {
    if (r < tl || tr < l)
        return 0;
    if (l <= tl && tr <= r) {
        return t[v];
    }
    int tm = (tl + tr) / 2;
    return sum(v*2, tl, tm, l, r) + sum(v*2+1, tm+1, tr, l, r);
}

This one here makes it a little easier to understand
These two methods do the same thing (they both work)

Let's say we want to find the sum in range [1, n/2]

[1, n/2+1] = [1, n/2]+[n/2+1, n/2+1] = t[2]+t[x]
l=1
r=n/2+1


l=3, r=8
tl=5, tr=7 --> t[v] = sum of range[5..7]
return t[v] //we want to include ALL of t[v]

void update(int v, int tl, int tr, int pos, int new_val) {
    if (tl == tr) {
        t[v] = new_val;
    } else {
        int tm = (tl + tr) / 2;
        if (pos <= tm)
            update(v*2, tl, tm, pos, new_val);
        else
            update(v*2+1, tm+1, tr, pos, new_val);
        t[v] = t[v*2] + t[v*2+1];
    }
}
posted @ 2022-10-03 02:32  wd_sun  阅读(30)  评论(0)    收藏  举报