Problem solution · C++

Point Add Rectangle Sum

Point Add Rectangle Sum: a C++ solution using segment tree or range structure. Learn the idea, check the complexity, and read the full code, with credit to NyaanNyaan Competitive Programming Library.

Technique
Segment tree or range structure
Source
NyaanNyaan Competitive Programming Library
Length
33 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Segment tree or range structure

For Point Add Rectangle Sum, the implementation stores interval information in a range-query data structure so updates and queries avoid rescanning the full input.

  1. Choose the aggregate stored for each interval or prefix.
  2. Build or initialize the structure from the input.
  3. Apply updates and combine the affected nodes to answer each query.

Code notes

  • 33 lines of C++ from the credited upstream file yosupo-point-add-rectangle-sum-wm.test.cpp.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Count the build once, then multiply the logarithmic update or query path by the number of operations.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from NyaanNyaan Competitive Programming Library by NyaanNyaan and is used under the CC0-1.0 licence.

Full codePoint Add Rectangle Sum · C++C++
Use this to learn the idea, then write your own version.
#define PROBLEM "https://judge.yosupo.jp/problem/point_add_rectangle_sum" #include "../../template/template.hpp"#include "../../data-structure-2d/fenwick-tree-on-wavelet-matrix.hpp"#include "../../misc/fastio.hpp" using namespace Nyaan; void Nyaan::solve() {  WaveletMatrix<int, ll> wm;   int N, Q;  rd(N, Q);  vector<int> X(N), Y(N), W(N), c(Q), s(Q), t(Q), u(Q), v(Q);  rep(i, N) {    rd(X[i], Y[i], W[i]);    wm.add_point(X[i], Y[i]);  }  rep(i, Q) {    rd(c[i], s[i], t[i], u[i]);    if (c[i])      rd(v[i]);    else      wm.add_point(s[i], t[i]);  }   wm.build();  rep(i, N) { wm.add(X[i], Y[i], W[i]); }  rep(i, Q) {    if (c[i]) {      out(wm.sum(s[i], t[i], u[i], v[i]));    } else      wm.add(s[i], t[i], u[i]);  }}

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗