---
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"], ""),
    ]
  }
};

<problems-list problems={metadata.problems.sample} />

<br/>

A **segment tree** allows you to do point update and range query in $O(\log N)$ time each for any associative operation. 

## Resources

<info-block title="Pro Tip">

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.

</info-block>

<resources>
  <resource source="CSA" title="Segment Trees" url="segment_trees" starred>interactive</resource>
  <resource source="CPH" title="9.3 - Segment Trees" starred>same implementation as below</resource>
  <resource source="CPC" title="3 - Data Structures" url="03_data_structures" starred>see slides after union-find</resource>
  <resource source="cp-algo" title="Segment Tree" url="data_structures/segment_tree.html" starred></resource>
  <resource source="PAPS" title="11.2.3 - Segment Trees"></resource>
</resources>

### Implementations

<resources>
  <resource source="CF" title="AICash - Efficient and easy segment trees" url="blog/entry/18051" starred>simple implementation</resource>
  <resource source="Benq" title="SegTree" url="https://github.com/bqi343/USACO/blob/master/Implementations/content/data-structures/1D%20Range%20Queries%20(9.2)/SegTree%20(9.2).h">based off above</resource>
</resources>

<LanguageSection>

<CPPSection>

```cpp
template<class T> struct Seg { // comb(ID,b) = b
  const T ID = 0; T comb(T a, T b) { return a+b; } 
  int n; vector<T> 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);
  }
};
```

</CPPSection>

<JavaSection>



</JavaSection>

</LanguageSection>

## Problems

Can also try solving some of tasks from both prerequisite articles.

<problems-list problems={metadata.problems.general} />
