--- id: PURQ title: "Point Update Range Query" author: Benjamin Qi prerequisites: - Gold - Point Update Range Sum - Gold - Max Suffix Query with Insertions Only description: "Range queries for any associative operation over an array with updates using segment tree." frequency: 1 --- import { Problem } from "../models"; export const metadata = { problems: { sample: [ new Problem("CSES", "Range Minimum Queries II", "1649", "Intro|Easy", false, ["PURQ"], ""), ], general: [ new Problem("YS", "Point Set Range Composite", "point_set_range_composite", "Easy", false, ["PURQ"], "Order of operations matters!"), new Problem("Plat", "Slingshot", "816", "Hard", false, ["PURQ"], ""), ] } };
A **segment tree** allows you to do point update and range query in $O(\log N)$ time each for any associative operation. ## Resources For gold, you only need to know the basics (ex. sum, min queries). You can skip more advanced applications such as **lazy propagation** for now. interactive same implementation as below see slides after union-find ### Implementations simple implementation based off above ```cpp template struct Seg { // comb(ID,b) = b const T ID = 0; T comb(T a, T b) { return a+b; } int n; vector seg; void init(int _n) { n = _n; seg.assign(2*n,ID); } void pull(int p) { seg[p] = comb(seg[2*p],seg[2*p+1]); } void upd(int p, T val) { // set val at position p seg[p += n] = val; for (p /= 2; p; p /= 2) pull(p); } T query(int l, int r) { // sum on interval [l, r] T ra = ID, rb = ID; for (l += n, r += n+1; l < r; l /= 2, r /= 2) { if (l&1) ra = comb(ra,seg[l++]); if (r&1) rb = comb(seg[--r],rb); } return comb(ra,rb); } }; ``` ## Problems Can also try solving some of tasks from both prerequisite articles.